hi i have a jtable with checkbox in column and column header
problem is if i click on the first column header, the first column header is select and the the second one
String[] columnNames = {"Am", "Pm", "Integer", "String"};
Object[][] data = {{true, true, 1, "BBB"}, {false, true, 12, "AAA"},
{true, false, 2, "DDD"}, {false, false, 5, "CCC"},
{true, true, 3, "EEE"}, {false, false, 6, "GGG"},
{true, true, 4, "FFF"}, {false, false, 7, "HHH"}};
DefaultTableModel model = new DefaultTableModel(data, columnNames) {
@Override
public Class<?> getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
JTable table = new JTable(model);
table.getColumnModel().getColumn(0).setHeaderRenderer(
new HeaderRenderer2(table.getTableHeader()));
table.getColumnModel().getColumn(1).setHeaderRenderer(
new HeaderRenderer2(table.getTableHeader()));
i created a table cell renderer
public class HeaderRenderer2 implements TableCellRenderer {
private final JCheckBox check = new JCheckBox();
public HeaderRenderer2(JTableHeader header) {
check.setOpaque(false);
check.setFont(header.getFont());
header.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
JTable table = ((JTableHeader) e.getSource()).getTable();
TableColumnModel columnModel = table.getColumnModel();
int viewColumn = columnModel.getColumnIndexAtX(e.getX());
int modelColumn = table.convertColumnIndexToModel(viewColumn);
if (modelColumn == 0) {
check.setSelected(!check.isSelected());
TableModel m = table.getModel();
Boolean f = check.isSelected();
for (int i = 0; i < m.getRowCount(); i++) {
m.setValueAt(f, i, 0);
}
((JTableHeader) e.getSource()).repaint();
}
}
});
}
@Override
public Component getTableCellRendererComponent(
JTable tbl, Object val, boolean isS, boolean hasF, int row, int col) {
TableCellRenderer r = tbl.getTableHeader().getDefaultRenderer();
JLabel l = (JLabel) r.getTableCellRendererComponent(tbl, val, isS, hasF, row, col);
l.setIcon(new CheckBoxIcon(check));
return l;
}
private static class CheckBoxIcon implements Icon {
private final JCheckBox check;
public CheckBoxIcon(JCheckBox check) {
this.check = check;
}
@Override
public int getIconWidth() {
return check.getPreferredSize().width;
}
@Override
public int getIconHeight() {
return check.getPreferredSize().height;
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
SwingUtilities.paintComponent(
g, check, (Container) c, x, y, getIconWidth(), getIconHeight());
}
}
}
image at the top nothing selected image at the bottom after a click on the column header (AM)
getTableCellRendererComponent happen before the mouseClicked event so i'm not able to get the clicked column
any idea?
The problem is in the mouse listener. Both instances are listing for mouse clicks on the header that have a column ==0. Therefore both get checked or unchecked when you click on that header.