如何将复选框添加到 JTABLE 摆动 [已关闭]

2022-09-03 08:44:13

有谁知道如何将一个放在列中?像这样:JCheckBoxJTable

Table from the table tutorial

我从如何使用表格中获取了这个

提前致谢。


答案 1

1)JTable知道JCheckbox默认内置布尔TableCellRenderers和TableCellEditor,那么有一些相反的生产性声明,

2)AbstractTableModel应该是有用的,其中是需要减少/限制/更改嵌套和继承方法,默认情况下在中实现,JTableDefaultTableModel

3)考虑使用 ,(如果您不确定如何工作)而不是 ,DefaultTableModelAbstractTableModel

table_with_BooleanType_column

可以从简单的代码生成:

import javax.swing.*;
import javax.swing.table.*;

public class TableCheckBox extends JFrame {

    private static final long serialVersionUID = 1L;
    private JTable table;

    public TableCheckBox() {
        Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
        Object[][] data = {
            {"Buy", "IBM", new Integer(1000), new Double(80.50), false},
            {"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
            {"Sell", "Apple", new Integer(3000), new Double(7.35), true},
            {"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
        };
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        table = new JTable(model) {

            private static final long serialVersionUID = 1L;

            /*@Override
            public Class getColumnClass(int column) {
            return getValueAt(0, column).getClass();
            }*/
            @Override
            public Class getColumnClass(int column) {
                switch (column) {
                    case 0:
                        return String.class;
                    case 1:
                        return String.class;
                    case 2:
                        return Integer.class;
                    case 3:
                        return Double.class;
                    default:
                        return Boolean.class;
                }
            }
        };
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        getContentPane().add(scrollPane);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                TableCheckBox frame = new TableCheckBox();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocation(150, 150);
                frame.setVisible(true);
            }
        });
    }
}

答案 2

推荐