在JTable中添加JCheckBox可以通过自定义TableCellRenderer和TableCellEditor来实现。
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
public class MyCheckBoxRenderer extends DefaultTableCellRenderer {
private MyCheckBox checkBox;
public MyCheckBoxRenderer() {
checkBox = new MyCheckBox();
checkBox.setHorizontalAlignment(JCheckBox.CENTER);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
checkBox.setSelected((Boolean) value);
return checkBox;
}
}
import javax.swing.*;
import javax.swing.table.DefaultCellEditor;
import java.awt.*;
public class MyCheckBoxEditor extends DefaultCellEditor {
private MyCheckBox checkBox;
public MyCheckBoxEditor() {
super(new MyCheckBox());
checkBox = (MyCheckBox) getComponent();
checkBox.setHorizontalAlignment(JCheckBox.CENTER);
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
checkBox.setSelected((Boolean) value);
return checkBox;
}
@Override
public Object getCellEditorValue() {
return checkBox.isSelected();
}
}
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
public class JTableWithCheckBox {
public static void main(String[] args) {
JFrame frame = new JFrame("JTable with CheckBox");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 创建表格模型
DefaultTableModel model = new DefaultTableModel(new Object[][]{
{false, "Item 1"},
{true, "Item 2"},
{false, "Item 3"},
{true, "Item 4"}
}, new Object[]{"Selected", "Name"});
// 创建表格
JTable table = new JTable(model);
// 设置列宽
TableColumn column = table.getColumnModel().getColumn(0);
column.setPreferredWidth(50);
// 应用自定义的渲染器和编辑器
column.setCellRenderer(new MyCheckBoxRenderer());
column.setCellEditor(new MyCheckBoxEditor());
// 添加表格到窗口
frame.getContentPane().add(new JScrollPane(table));
frame.pack();
frame.setVisible(true);
}
}
这样,就可以在JTable中的指定列中显示复选框,并且可以进行选择和编辑。
领取专属 10元无门槛券
手把手带您无忧上云