I want to recreate a table header looks using JLabel
. The look and feel of the JLabel
needs to be exactly like the JTableHeader
would
You need to set a look and feel for the application before trying:
header.setBackground(UIManager.getColor(new JTableHeader().getBackground()));
header.setBorder(UIManager.getBorder(new JTableHeader().getBorder()));
you should set a look and feel first like so:
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.
}
Here is an example:
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.JTableHeader;
public class Test {
public Test() {
initComponents();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
//set nimbus look and feel
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
new Test();
}
});
}
private void initComponents() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel header = new JLabel("Title");
header.setBackground(UIManager.getColor(new JTableHeader().getBackground()));
header.setBorder(UIManager.getBorder(new JTableHeader().getBorder()));
frame.add(header);
frame.pack();
frame.setVisible(true);
}
}