使用JComboBox作为编辑器的JTable - 删除当前行

时间:2014-02-25 07:25:30

标签: java swing jtable jcombobox tablecelleditor

我想实现一个JTable,其中有一列JComboBox作为编辑器。我希望我的表最初只有一行。在ComboBox中设置值后,我希望我的表格中填充一些值,具体取决于JComboBox的所选元素。选择非空元素后,我想向表中添加新行。当有多个行不为空且有人将第n个组合框的值设置为空时,我想从表中删除该行。

简单的解决方案不起作用:

TableColumn column = table.getColumnModel().getColumn(2);
JComboBox comboBox = new JComboBox();
comboBox.addItem("");
comboBox.addItem("1");
comboBox.addItem("2");
comboBox.addItem("3");
comboBox.addItem("4");
comboBox.addItem("5");
comboBox.addItemListener(new ItemListener() {
    public void itemStateChanged(ItemEvent e) {
        JComboBox combo = (JComboBox)e.getSource();
        if (combo.getSelectedItem() != null) {
            if (combo.getSelectedItem().equals("")) {
                table.getTableModel().removeRow(table.getSelectedRow());
            } else {
                table.getTableModel().addRow(new Object[] {null, null, null, null});
            }
        }
    }
});
column.setCellEditor(new DefaultCellEditor(comboBox));

1 个答案:

答案 0 :(得分:2)

根据mKorbel的建议,只需在TableModel setValueAt(...)方法中实施该逻辑即可。这是一个简单的例子:

import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

public class Example extends JFrame {

    private JTable table;

    public Example(){
        table = getTable();
        add(new JScrollPane(table));

        pack();
        setVisible(true);
    }

    private JTable getTable() {
        table = new JTable(new DefaultTableModel(3,3){
            @Override
            public void setValueAt(Object aValue, int row, int column) {
                super.setValueAt(aValue, row, column);
                if(column == 2){
                    if(aValue.toString().isEmpty()){
                        removeRow(row);
                    } else {
                        addRow(new Object[] {null, null, null});
                    }
                }
            }
        });
        TableColumn column = table.getColumnModel().getColumn(2);
        JComboBox<String> comboBox = new JComboBox<>(new String[]{"","1","2","3","4","5"});
        column.setCellEditor(new DefaultCellEditor(comboBox));
        return table;
    }

    public static void main(String[] values){
        new Example();
    }

}