简体   繁体   English

Java Swing - 通知GUI有关模型的更改

[英]Java Swing - inform GUI about changes to the model

I have a column in JTable that binds to the underlying boolean property on a list of business objects. 我在JTable中有一个列绑定到业务对象列表上的底层布尔属性。 I also have a combobox, which should select which items should be selected. 我还有一个组合框,应该选择应该选择哪些项目。 I basically added the following code as a handler to the combobox: 我基本上将以下代码添加为组合框的处理程序:

            macroCombo.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    JComboBox comboBox = (JComboBox) e.getSource();
                    Predicate filter = (Predicate) comboBox.getSelectedItem();
                    for(SelectableKey key : tableEntries){
                        key.setSelected(filter.evaluate(key));
                    }
                }
            });

I also have a few other controls I want to change based on the value. 我还想根据值改变一些其他控件。 At the moment, only a few cells in the table change their state to be selected/deselected. 目前,表中只有少数单元格会更改其状态以进行选择/取消选择。 Only when I click on the row, or select multiple rows, the UI updates itself. 只有当我单击该行或选择多行时,UI才会自行更新。 Is there a call from the handler I need to make to tell GUI to redraw itself? 是否有来自我需要做的处理程序的调用来告诉GUI重绘自己? ALos, if I modify other controls than JTable, how would I tell them to change their state? ALOS,如果我修改除JTable之外的其他控件,我怎么告诉他们改变他们的状态?

Thanks 谢谢

When you update a value in your TableModel , the model should fire a corresponding TableModelEvent (type: UPDATE ). 当您更新TableModel的值时,模型应该触发相应的TableModelEvent (类型: UPDATE )。

If your TableModel for example extends from AbstractTableModel , you can call the fireTableRowsUpdated method after you have made the changes. 例如,如果您的TableModelAbstractTableModel扩展,则可以在进行更改后调用fireTableRowsUpdated方法。

Another approach is a TableModel which knows when it gets updated (for example by adding listeners to the objects it contains). 另一种方法是TableModel ,它知道何时更新(例如通过向其包含的对象添加侦听器)。 This allows other code to simply update the objects contained in the TableModel , without having knowledge of the TableModel . 这允许其他代码简单地更新TableModel包含的对象,而无需了解TableModel The TableModel itself will then fire the event when it detects changes made to the objects it contains. 然后,当TableModel检测到对其包含的对象所做的更改时,它将自动触发该事件。

I prefer the second approach, as this avoids that I have to pass that TableModel around to all my other classes. 我更喜欢第二种方法,因为这避免了我必须将TableModel传递给我所有其他类。

Consult the table tutorial for more information. 有关更多信息,请参阅表格教程

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

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