给jtable设置单选框的代码和注释
时间: 2023-06-05 10:06:21 浏览: 134
以下是Java Swing中给JTable设置单选框的代码和注释:
```java
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
import java.awt.*;
public class JTableRadioButton extends JFrame {
private JTable table;
public JTableRadioButton() {
setTitle("JTable Radio Button Example");
// 创建表数据
Object[][] data = {
{new Boolean(false), "John Doe", "1-555-555-5555"},
{new Boolean(false), "Mary Jane", "1-555-555-1234"},
{new Boolean(false), "Bob Smith", "1-555-555-9876"},
{new Boolean(false), "Jane Doe", "1-555-555-5555"}
};
// 创建表头
String[] columnNames = {"Selected", "Name", "Phone Number"};
// 创建表模型,并设置数据和表头
DefaultTableModel model = new DefaultTableModel(data, columnNames);
// 创建表并设置模型
table = new JTable(model);
// 获取表格控制器
TableColumnModel columnModel = table.getColumnModel();
// 获取单选框列,并将它的宽度设置为100像素
int radioButtonColumnIndex = 0;
columnModel.getColumn(radioButtonColumnIndex).setPreferredWidth(100);
// 设置单选框渲染器和编辑器
columnModel.getColumn(radioButtonColumnIndex).setCellRenderer(new RadioButtonRenderer());
columnModel.getColumn(radioButtonColumnIndex).setCellEditor(new RadioButtonEditor(new JCheckBox()));
// 将表格添加到窗口中
add(new JScrollPane(table));
// 设置窗口大小并可见
setSize(400, 200);
setVisible(true);
}
// 单选框渲染器
class RadioButtonRenderer implements TableCellRenderer {
private JRadioButton radioButton = new JRadioButton();
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value != null) {
radioButton.setSelected(((Boolean) value).booleanValue());
} else {
radioButton.setSelected(false);
}
return radioButton;
}
}
// 单选框编辑器
class RadioButtonEditor extends DefaultCellEditor implements ItemListener {
private JRadioButton radioButton;
public RadioButtonEditor(JCheckBox checkBox) {
super(checkBox);
radioButton = new JRadioButton();
radioButton.addItemListener(this);
}
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
if (value != null) {
radioButton.setSelected(((Boolean) value).booleanValue());
} else {
radioButton.setSelected(false);
}
return radioButton;
}
public Object getCellEditorValue() {
return Boolean.valueOf(radioButton.isSelected());
}
public void itemStateChanged(ItemEvent e) {
super.fireEditingStopped();
}
}
public static void main(String[] args) {
new JTableRadioButton();
}
}
```
注释中解释了代码中每个部分所做的事情。建议您看懂代码后再使用它,这样才能更好地理解它是如何实现的。
阅读全文