在JTable中替换布尔CheckBox渲染器/编辑器,可以通过自定义TableCellRenderer和TableCellEditor来实现。
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
public class BooleanCheckBoxRenderer extends DefaultTableCellRenderer {
private JCheckBox checkBox;
public BooleanCheckBoxRenderer() {
checkBox = new JCheckBox();
checkBox.setHorizontalAlignment(JCheckBox.CENTER);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value != null && value instanceof Boolean) {
checkBox.setSelected((Boolean) value);
}
return checkBox;
}
}
import javax.swing.*;
import javax.swing.table.DefaultCellEditor;
import java.awt.*;
public class BooleanCheckBoxEditor extends DefaultCellEditor {
private JCheckBox checkBox;
public BooleanCheckBoxEditor() {
super(new JCheckBox());
checkBox = (JCheckBox) getComponent();
checkBox.setHorizontalAlignment(JCheckBox.CENTER);
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
if (value != null && value instanceof Boolean) {
checkBox.setSelected((Boolean) value);
}
return checkBox;
}
@Override
public Object getCellEditorValue() {
return checkBox.isSelected();
}
}
JTable table = new JTable();
TableColumn column = table.getColumnModel().getColumn(columnIndex);
column.setCellRenderer(new BooleanCheckBoxRenderer());
column.setCellEditor(new BooleanCheckBoxEditor());
这样,当JTable中的布尔类型数据在对应列中显示时,会以CheckBox的形式展示,并且可以进行编辑。
推荐的腾讯云相关产品:腾讯云云服务器(CVM) 产品介绍链接地址:https://cloud.tencent.com/product/cvm
领取专属 10元无门槛券
手把手带您无忧上云