简体   繁体   中英

Swing JTable reset TableCellEditor

JComboBox in TableCellEditor remember last selected value among different rows and even different TableModels . For example select a value on one row, then go to another row, start cell editing and JComboBox will have as its current value last select value on the previos row.

How can it fixed?

Set the value in the getTableCellEditorComponent(..) method.

Example:

public static void main(String... args) {

    JFrame frame = new JFrame("Test");

    JTable table = new JTable(10, 2);
    JComboBox box = new JComboBox(new String[] {"A", "B", "C"});
    table.setDefaultEditor(Object.class, new DefaultCellEditor(box) {

        @Override
        public Component getTableCellEditorComponent(JTable table,
                Object value, boolean isSelected, int row, int column) {
            return super.getTableCellEditorComponent(
                        table, 
                        table.getValueAt(Math.max(row-1, 0), column), 
                        isSelected, 
                        row, 
                        column);
        }
    });

    frame.add(table);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 300);
    frame.setVisible(true);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM