我有一个包含3列的表,第一列是特殊的,包含一个复选框而不是标题。
问题是复选框标题的布局(外观)与其他标题不同。有人可以帮忙吗?
守则:
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.event.*;
public class JTableHeaderCheckBox
{
Object colNames[] = {"", "String", "String"};
Object[][] data = {};
DefaultTableModel dtm;
JTable table;
public void buildGUI()
{
dtm = new DefaultTableModel(data,colNames);
table = new JTable(dtm);
for(int x = 0; x < 2; x++)
{
dtm.addRow(new Object[]{new Boolean(false),"Row "+(x+1)+" Col 2","Row "+(x+1)+" Col 3"});
}
JScrollPane sp = new JScrollPane(table);
TableColumn tc = table.getColumnModel().getColumn(0);
tc.setCellEditor(table.getDefaultEditor(Boolean.class));
tc.setCellRenderer(table.getDefaultRenderer(Boolean.class));
tc.setHeaderRenderer(new CheckBoxHeader());
JFrame f = new JFrame();
f.getContentPane().add(sp);
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public static void main (String[] args)
{
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new JTableHeaderCheckBox().buildGUI();
}
});
}
}
class CheckBoxHeader extends JCheckBox implements TableCellRenderer {
protected CheckBoxHeader rendererComponent;
protected int column;
public CheckBoxHeader() {
rendererComponent = this;
}
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
setColumn(column);
return rendererComponent;
}
protected void setColumn(int column) {
this.column = column;
}
public int getColumn() {
return column;
}
}
奇怪的输出:
更新
我想要的是什么:
答案 0 :(得分:4)
如果您指的是复选框的边框,可以尝试使其更加一致:
public CheckBoxHeader() {
rendererComponent = this;
setHorizontalAlignment(JLabel.CENTER);
setBorderPaintedFlat(true);
setBorderPainted(true);
}
答案 1 :(得分:3)
TableCellRenderer
会返回JLabel/JComponents
和这些JComponents haven't got implemented any LayoutManager,但对LayoutManagers