给jtable添加单选
时间: 2023-06-05 07:06:18 浏览: 129
按钮列。这个问题属于技术问题,我可以帮助您回答。要给JTable添加单选按钮列,可以使用JRadioButton作为渲染器和编辑器,代码示例如下:
```java
JTable table = new JTable();
TableColumn radioColumn = new TableColumn();
radioColumn.setCellRenderer(new RadioButtonRenderer());
radioColumn.setCellEditor(new RadioButtonEditor(new JCheckBox()));
table.addColumn(radioColumn);
// 自定义单选按钮渲染器
class RadioButtonRenderer extends JRadioButton implements TableCellRenderer {
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value != null) {
setSelected((Boolean) value);
}
return this;
}
}
// 自定义单选按钮编辑器
class RadioButtonEditor extends DefaultCellEditor implements ItemListener {
private JRadioButton button;
public RadioButtonEditor(JCheckBox checkBox) {
super(checkBox);
}
public Component getTableCellEditorComponent(
JTable table, Object value, boolean isSelected, int row, int column) {
if (value == null) {
button = new JRadioButton();
} else {
button = new JRadioButton(((Boolean) value).toString());
}
button.addItemListener(this);
return button;
}
public Object getCellEditorValue() {
button.removeItemListener(this);
return button.isSelected();
}
public void itemStateChanged(ItemEvent e) {
super.fireEditingStopped();
}
}
```
阅读全文