如何给jtable添加单选框
时间: 2023-06-05 18:06:24 浏览: 157
您好,可以使用JRadioButton作为单选框,然后将其添加到JTable的表格中,具体实现可以通过继承AbstractTableModel,重写getColumnClass方法,将对应列的Class设置为JRadioButton即可。具体代码实现如下:
```
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
public class MyTableModel extends AbstractTableModel {
private Object[][] rowData = {
{"1", "option1"},
{"2", "option2"},
{"3", "option3"},
};
private String[] columnNames = {"ID", "Options"};
private JRadioButton[][] radioButtons = new JRadioButton[rowData.length][1];
@Override
public int getRowCount() {
return rowData.length;
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
if (columnIndex == 0) {
return rowData[rowIndex][columnIndex];
} else {
JRadioButton radioButton = radioButtons[rowIndex][columnIndex - 1];
if (radioButton == null) {
radioButton = new JRadioButton();
radioButtons[rowIndex][columnIndex - 1] = radioButton;
}
return radioButton;
}
}
@Override
public String getColumnName(int column) {
return columnNames[column];
}
@Override
public Class<?> getColumnClass(int columnIndex) {
if (columnIndex == 0) {
return Integer.class;
} else {
return JRadioButton.class;
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("JTable with JRadioButton");
frame.setSize(400, 300);
JTable table = new JTable(new MyTableModel());
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
```
阅读全文