在单击JCheckBox时禁用JTable中的JComboBox

时间:2012-05-23 16:16:01

标签: java swing jtable jcombobox jcheckbox

我有JTable,并且在两个不同的列中有JCheckBoxJComoboBox。当我选择与该行对应的JCheckBox时,应禁用JComboBox。请帮助我。

1 个答案:

答案 0 :(得分:4)

只需根据您的型号禁用单元格编辑。在TableModel中,覆盖/实现isCellEditable()方法以返回复选框的“值”。

虽然以下示例不是基于JComboBox,但它说明了如何根据行开头的复选框值禁用单元格的编辑:

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

public class TestTable {

    public JFrame f;
    private JTable table;

    public class TestTableModel extends DefaultTableModel {

        public TestTableModel() {
            super(new String[] { "Editable", "DATA" }, 3);
            for (int i = 0; i < 3; i++) {
                setValueAt(Boolean.TRUE, i, 0);
                setValueAt(Double.valueOf(i), i, 1);
            }
        }

        @Override
        public boolean isCellEditable(int row, int column) {
            if (column == 1) {
                return (Boolean) getValueAt(row, 0);
            }
            return super.isCellEditable(row, column);
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            if (columnIndex == 0) {
                return Boolean.class;
            } else if (columnIndex == 1) {
                return Double.class;
            }
            return super.getColumnClass(columnIndex);
        }
    }

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

            @Override
            public void run() {
                new TestTable().initUI();
            }
        });
    }

    protected void initUI() {
        table = new JTable(new TestTableModel());
        f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(300, 300);
        f.setLocationRelativeTo(null);
        f.add(new JScrollPane(table));
        f.setVisible(true);
    }

}