Display JCheckBox in JTable

帅比萌擦擦* 提交于 2019-11-27 09:53:15
  1. don't add components to your TableModel, that's not the responsibility of the TableModel
  2. You will need to specify the class type of your column. Assuming you're using a DefaultTableModel, you can simply fill the column with a bunch of booleans and this should work - After testing, you will need to override the getColumnClass method of the DefaultTableModel (or what ever TableModel implementation) and make sure that for the "check box" column, it returns Boolean.class

See How to use tables for more details

For example...

import java.awt.EventQueue;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;

public class TestCardLayout {

    public static void main(String[] args) {
        new TestCardLayout();
    }

    public TestCardLayout() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                Random rnd = new Random();
                DefaultTableModel model = new DefaultTableModel(new Object[]{"Check boxes"}, 0) {

                    @Override
                    public Class<?> getColumnClass(int columnIndex) {
                        return Boolean.class;
                    }

                };
                for (int index = 0; index < 10; index++) {
                    model.addRow(new Object[]{rnd.nextBoolean()});
                }
                JTable table = new JTable(model);

                final JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new JScrollPane(table));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!