防止复选框在 JTable 中移动
我在 JTable 中有一个列,其单元格呈现为下面的复选框:
如何防止每次我点击它时复选框都会移动?这是我的单元格渲染器和单元格编辑器:
protected class CheckBoxCellRenderer extends JCheckBox implements TableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
this.setSelected((Boolean) tableModel.getValueAt(row, 0));
return this;
}
}
protected class CheckBoxCellEditor extends AbstractCellEditor implements TableCellEditor, ActionListener {
private final CheckBoxCellRenderer cell = new CheckBoxCellRenderer();
private int row;
public CheckBoxCellEditor() {
cell.addActionListener(this);
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int rowIndex, int vColIndex) {
cell.setSelected(((Boolean) value).booleanValue());
row = rowIndex;
return cell;
}
@Override
public Object getCellEditorValue() {
return cell.isSelected();
}
}
谢谢!
I have a column in a JTable with cells rendered as checkboxes below:
How do I prevent the checkboxes from moving every time I click on it? Here is my cell renderer and cell editor:
protected class CheckBoxCellRenderer extends JCheckBox implements TableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
this.setSelected((Boolean) tableModel.getValueAt(row, 0));
return this;
}
}
protected class CheckBoxCellEditor extends AbstractCellEditor implements TableCellEditor, ActionListener {
private final CheckBoxCellRenderer cell = new CheckBoxCellRenderer();
private int row;
public CheckBoxCellEditor() {
cell.addActionListener(this);
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int rowIndex, int vColIndex) {
cell.setSelected(((Boolean) value).booleanValue());
row = rowIndex;
return cell;
}
@Override
public Object getCellEditorValue() {
return cell.isSelected();
}
}
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不要创建自定义渲染器/编辑器。
JTable 已经支持默认渲染器。只需重写 TableModel 或 JTable 的 getColumnClass(...) 方法即可返回第一列的 Boolean.class,JTable 将使用默认渲染器/编辑器。
Don't create a custom renderer/editor.
JTable already supports a default renderer. Just override the getColumnClass(...) method of the TableModel or JTable to return Boolean.class for the first column and the JTable will use the default renderer/editor.