怎么在jtable的列前面加单选框附上代码和注释
时间: 2023-06-05 20:06:50 浏览: 125
对于您的问题,在jtable的列前面加单选框可以通过自定义TableCellRenderer和TableCellEditor来实现。下面是一个例子:
```
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractCellEditor;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
public class JTableExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JTable Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Object[] columnNames = {"Name", "Age", "Gender", "Select"};
Object[][] rowData = {
{"John Doe", 30, "Male", false},
{"Jane Doe", 25, "Female", false},
{"Bob Smith", 40, "Male", false},
{"Alice Jones", 35, "Female", false}
};
DefaultTableModel model = new DefaultTableModel(rowData, columnNames);
JTable table = new JTable(model) {
@Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
table.getColumnModel().getColumn(3).setCellRenderer(new RadioButtonRenderer());
table.getColumnModel().getColumn(3).setCellEditor(new RadioButtonEditor(new JCheckBox()));
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane);
frame.pack();
frame.setVisible(true);
}
static class RadioButtonRenderer extends JCheckBox implements TableCellRenderer {
public RadioButtonRenderer() {
setOpaque(true);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value != null) {
setSelected((Boolean) value);
}
return this;
}
}
static class RadioButtonEditor extends AbstractCellEditor implements TableCellEditor, ActionListener {
private JCheckBox checkBox;
public RadioButtonEditor(JCheckBox checkBox) {
this.checkBox = checkBox;
checkBox.addActionListener(this);
}
@Override
public Object getCellEditorValue() {
return checkBox.isSelected();
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
if (value != null) {
checkBox.setSelected((Boolean) value);
}
return checkBox;
}
@Override
public void actionPerformed(ActionEvent e) {
fireEditingStopped();
}
}
}
```
这个例子中,我们创建了一张包含"Name"、"Age"、"Gender"、"Select"这四列的表格,并给"Select"这一列加上了单选框,可以让用户在表格中选择一行数据。可以根据需要修改列名和数据,然后添加到您的项目中。
阅读全文