简体   繁体   English

JTable中的JComboBox不会在项目更改时立即更新表

[英]JComboBox in JTable does not update table instantly on item change

I have a JTable with JComboBoxes as the cell editor for one of the columns. 我有一个带有JComboBoxes的JTable作为其中一列的单元格编辑器。 When a user clicks one of the options in one of the comboboxes, the table cell should instantly be set to whatever option was chosen from the combobox. 当用户单击组合框之一中的选项之一时,表格单元格应立即设置为从组合框中选择的任何选项。 Sadly however, this does not happen until the user clicks elsewhere or presses Enter. 但是,令人遗憾的是,直到用户单击其他位置或按Enter键,这种情况才会发生。

I understand that I could just take the value from the combobox but I would like to save the table to a file as soon as an option is chosen from any combobox in the table, and I haven't been able to find a way to dynamically identify which row a combobox belongs to so that the table could be updated on item change. 我了解我可以只从组合框中获取值,但是一旦从表中的任何组合框中选择了一个选项,我都希望将表保存到文件中,而我一直无法找到一种动态方式确定组合框属于哪一行,以便可以在项目更改时更新表格。

Is there a way to get the table to update with the chosen value as soon as the combobox item listener is fired? 有没有一种方法可以在激发组合框项目侦听器后立即使表以选定的值更新?

Here is an example demonstrating this issue: 这是演示此问题的示例:

public static void main(String args[]) {
    JFrame frame = new JFrame();
    frame.setSize(450, 250);

    JTable table = new JTable(2, 1);

    TableColumn testColumn = table.getColumnModel().getColumn(0);

    JComboBox<String> comboBox = new JComboBox<String>();
    comboBox.addItem("Item1");
    comboBox.addItem("Item2");
    comboBox.addItem("Item3");
    testColumn.setCellEditor(new DefaultCellEditor(comboBox));

    comboBox.addItemListener(new ItemListener(){
        @Override
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED){
                System.out.println(table.getValueAt(0, 0));
            }
        }
    });

    frame.add(table);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

Is there a way to get the table to update with the chosen value as soon as the combobox item listener is fired? 有没有一种方法可以在激发组合框项目侦听器后立即使表以选定的值更新?

Don't depend on the ItemListener (or ActionListener). 不要依赖ItemListener(或ActionListener)。 These events just indicate that the selected item of the combo box has changed. 这些事件仅表明组合框的所选项目已更改。

Now the editor will take control and remove itself from the table and update the TableModel with the selected value. 现在,编辑器将控制并从表中删除自身,并使用所选值更新TableModel

If you want to know when data is changed in the TableModel , then add a TableModelListener to the TableModel . 如果你想知道当数据在发生变化TableModel ,然后添加一个TableModelListenerTableModel

A TableModelEvent will be generated indicating the data has changed. 将生成一个TableModelEvent指示数据已更改。

See: JTable -> TableModeListener for a simple example. 请参见: JTable-> TableModeListener作为一个简单示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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