简体   繁体   English

Java Swing-如何更新GUI对象。 来自同一包中的子类的JTextField值

[英]Java Swing - how to update GUI Objects ie. JTextField value from sub class in same package

I have a GUI designed in Swing with all of the Components laid out. 我有一个在Swing中设计的GUI,其中包含了所有组件。 For example I have a JComboBox with a JList and a JTextField, 例如,我有一个带有JList和JTextField的JComboBox,

When I select a different item from the JComboBox I am trying to use a ListSelectionListener to call a method in a subclass to update the JTextField based on the choice, 当我从JComboBox中选择一个不同的项时,我试图使用ListSelectionListener来调用子类中的方法来根据选择更新JTextField,

How would I go about doing that properly? 我将如何正确地做到这一点? How do I call the subclass and then from the subclass update the GUI object's value? 如何调用子类,然后从子类更新GUI对象的值?

public class Parent {

    private void init() {
        // ...
        combo.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Object selected = combo.getSelectedItem();
                textField.setText(getTextBasedOnSelection(selected));
            }
        });
        // ...
    }

    /**
     * Returns the text to display when the given object is selected.
     * Subclasses may override this method to display what they want
     */
    protected String getTextBasedOnSelection(Object selected) {
        return selected.toString();
    }
    // ...
}

I hope I get your problem right. 我希望我能解决你的问题。 You have a View Component with several subviews and you want to update one because of the changes done inside the other one. 您有一个包含多个子视图的视图组件,并且您希望更新一个子视图,因为在另一个子视图中进行了更改。

Therefore you write an action listener for your combobox in the main View: 因此,您可以在主视图中为组合框编写一个动作侦听器:

comboBox.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent arg0) {
                textField.setText(comboBox.getSelectedItem());
            }

        });

Instead of inter-connecting components directly, I recommend to apply the Mediator pattern : Create a subclass of JPanel (eg XyzPane) where you put all your components in. This class becomes the Mediator. 我建议不要直接互连组件,而是应用Mediator模式 :创建一个JPanel的子类(例如XyzPane),放置所有组件。此类成为Mediator。 It

  • listens for events of its components 侦听其组件的事件
  • updates the components as needed 根据需要更新组件
  • fires its own events, if needed (this allows it to be a part of a parent Mediator: grouping components in Panes and then nesting the Panes) 如有必要,触发自己的事件(这使其成为父调解器的一部分:将“窗格”中的组件分组,然后嵌套“窗格”)

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

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