首页 > 解决方案 > JTableCell 中的 JCheckBox 在单击时出现和消失

问题描述

我有一个表,其中一列需要是“复选框列”。我写了这样的代码。

import javax.swing.DefaultCellEditor;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;

public class Test0 {
    
    public static void main(String... args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                Test0 test = new Test0();
                test.launch();
            }
            
        });
    }
    
    private void launch() {
        JFrame frame = new JFrame();
        Object[][] data = {{Boolean.TRUE}};
        String[] columnName = {"Checkbox here!"};
        @SuppressWarnings("serial")
        JTable table = new JTable(new DefaultTableModel(data,columnName) {
            @Override
            public Class<?> getColumnClass(int columnIndex){
                return Boolean.class;
            }
        });
        JCheckBox checkBox = new JCheckBox("HI");
        table.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(checkBox));
        JScrollPane tableScrollPane = new JScrollPane(table);
        frame.add(tableScrollPane);
        frame.pack();
        frame.setVisible(true);
    }
}

当我运行它时,带有“HI”标签的复选框并不像我想要的那样。相反,出现了一个普通的复选框,当我单击它时,我的复选框出现并迅速消失。我不明白是什么原因造成的。请帮我。谢谢你。

标签: javaswingjtable

解决方案


推荐阅读