JTable单元格编辑器更改类型

时间:2013-12-13 18:50:35

标签: java swing jtable jcombobox tablecelleditor

我有一个应该是2列的JTable(String,JComboBox)。当我初始化表时,一切看起来都很好。只要我在表中选择一个值,JComboBox单元就会获取所选项的数据类型。

我想保留JCOmboBox并让它触发数据更改事件,Table忽略该列中的数据更改并保持ComboBox的填充。

我的表格将此作为覆盖

@Override
public TableCellEditor getCellEditor(int row, int column) {
    Object value = super.getValueAt(row, column);
    if (value != null) {
        if (value instanceof JComboBox) {
            return new DefaultCellEditor((JComboBox) value);
        }
        return getDefaultEditor(value.getClass());
    }
    return super.getCellEditor(row, column);
}

实施

    JComboBox uploadBox = new JComboBox();
    uploadBox.addItem(MyPanel.UPLOAD_OPTIONS.PROMPT);
    uploadBox.addItem(MyPanel.UPLOAD_OPTIONS.UPLOAD);
    uploadBox.addItem(MyPanel.UPLOAD_OPTIONS.DONT_UPLOAD);

    Object[][] tableData = new Object[][]{
        {"Upload data on save", uploadBox}
    };



    table.setModel(
            new DefaultTableModel(tableData, new String[]{"Description", "Options"}) {
        Class[] types = new Class[]{String.class, JComboBox.class};
        boolean[] canEdit = new boolean[]{false, true};

        @Override
        public Class getColumnClass(int columnIndex) {
            return types[columnIndex];
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return canEdit[columnIndex];
        }


    });

    table.getColumnModel().getColumn(1).setCellRenderer(new TableCellRenderer() {

        @Override
        public Component getTableCellRendererComponent(JTable jtable, Object o, boolean bln, boolean bln1, int i, int i1) {
            return (Component)o;
        }
    });

1 个答案:

答案 0 :(得分:3)

  • 回答非常简单,不要将JComboBox添加到XxxTableModel或为getColumClass设置JComboBox.class,这是错误的(确定可行,但是一堆副作用),XxxTableModel(指定用于)只能直接保存标准Java数据类型(StringDateIcon / ImageIcon,{ {1}},Integer等......)

  • Double应该存储(如果你不想在Java数据类型之间解析)相同的数据类型,如XxxTableModel中存储的那样(注意清楚是什么constans {{ 1}}),例如,当DefaultComboBoxModel具有相同的数据类型时MyPanel.XXX存储XxxTableModel值,StringDefaultComboBoxModel / {{1}的类似逻辑}},DateIcon

  • 有关阅读Oracle教程How to use Tables - Using a Combo Box as an Editor

  • 的更多信息