java jtable添加jcheckbox
时间: 2023-08-21 11:06:24 浏览: 158
JTable添加CheckBox
5星 · 资源好评率100%
要在Java JTable中添加JCheckBox,需要创建一个自定义的TableCellEditor和TableCellRenderer。下面是一个简单的例子:
```java
import java.awt.Component;
import javax.swing.AbstractCellEditor;
import javax.swing.JCheckBox;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
public class CheckBoxCellEditorRenderer extends AbstractCellEditor implements TableCellEditor, TableCellRenderer {
private static final long serialVersionUID = 1L;
private JCheckBox checkBox;
public CheckBoxCellEditorRenderer() {
checkBox = new JCheckBox();
checkBox.setHorizontalAlignment(JCheckBox.CENTER);
}
@Override
public Object getCellEditorValue() {
return checkBox.isSelected();
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
checkBox.setSelected((Boolean) value);
return checkBox;
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
checkBox.setSelected((Boolean) value);
return checkBox;
}
}
```
然后,在创建JTable时,将该自定义的TableCellEditor和TableCellRenderer设置到JTable中的指定列即可,例如:
```java
JTable table = new JTable();
table.getColumnModel().getColumn(0).setCellEditor(new CheckBoxCellEditorRenderer());
table.getColumnModel().getColumn(0).setCellRenderer(new CheckBoxCellEditorRenderer());
```
这样,第一列就会显示JCheckBox了。
阅读全文