我正在尝试用JPanel替换JTable标题单元格(JLabel)。原因是有一个更灵活的容器来放置其他标题相关的东西,即多列排序指标。放置一个面板是直截了当的,但保持LAF似乎很麻烦。
我的尝试是覆盖标题渲染器并将内容打包到JPanel中。它可以工作,但默认的LAF已经按预期消失了。
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
public class JTableHeaderExperimental {
static class XTableHeaderCellRenderer extends DefaultTableCellRenderer{
private TableCellRenderer defaultRenderer;
public XTableHeaderCellRenderer(TableCellRenderer defaultRenderer) {
this.defaultRenderer = defaultRenderer;
}
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
// For the simplicity, skipping sorting icon related stuff
GridBagConstraints constraints = new GridBagConstraints();
JPanel panel = new JPanel(new GridBagLayout());
JLabel extraLabel = new JLabel("Extra label");
JLabel originalLabel = (JLabel) defaultRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 0;
constraints.gridy = 0;
panel.add(extraLabel, constraints);
constraints.gridx = 0;
constraints.gridy = 1;
panel.add(this, constraints);
System.out.println("Original Header Border: " + originalLabel.getBorder().getClass());
System.out.println("New Header Border: " + this.getBorder().getClass());
System.out.println("Header Panel Border: " + panel.getBorder().getClass());
return panel;
}
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
Object[][] data = {
{"Test", "Data"},
{"Comes", "Here"}
};
String[] columnNames = {"Header 1", "Header 2"};
JFrame frame = new JFrame();
JTable table = new JTable();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table.setModel(model);
table.getTableHeader().setDefaultRenderer(new XTableHeaderCellRenderer(table.getTableHeader().getDefaultRenderer()));
frame.setSize(200, 200);
frame.add(new JScrollPane(table));
frame.setVisible(true);
}
}
运行此代码会输出:
Original Header Border: class javax.swing.plaf.synth.SynthBorder
New Header Border: class javax.swing.border.EmptyBorder
Header Panel Border: class javax.swing.plaf.synth.SynthBorder
并呈现:
而不是默认系统LAF:
我想知道是否可以创建一个面板并传递原始标签的LAF细节(即边框,bg / fg颜色)。