jtable添加多选框
时间: 2023-11-17 11:07:13 浏览: 36
要在JTable中添加多选框,你需要使用一个自定义的渲染器和编辑器。以下是一个简单的示例,可以帮助你实现这个功能:
```java
import javax.swing.*;
import javax.swing.table.*;
public class CheckBoxTableExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Checkbox Table Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Object[][] data = {
{"John", false},
{"Mary", false},
{"Mike", false},
{"Lisa", false}
};
String[] columnNames = {"Name", "Select"};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable(model) {
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
TableColumn selectColumn = table.getColumnModel().getColumn(1);
selectColumn.setCellEditor(table.getDefaultEditor(Boolean.class));
selectColumn.setCellRenderer(table.getDefaultRenderer(Boolean.class));
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane);
frame.pack();
frame.setVisible(true);
}
}
```
在这个例子中,我们首先创建了一个包含两列的表格。第一列是一个字符串,第二列是一个布尔值(多选框)。然后,我们使用默认的表格模型创建了一个JTable。为了使多选框正常工作,我们需要设置渲染器和编辑器。我们通过getColumnModel方法获取到第二列,然后调用setCellEditor和setCellRenderer方法来设置编辑器和渲染器。最后,我们将表格添加到一个JScrollPane中,并将其添加到窗口中。
希望这个例子可以帮助你实现在JTable中添加多选框的功能。
相关推荐
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)