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. For example I have a JComboBox with a JList and a JTextField,

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,

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?

Answers


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 (e.g. XyzPane) where you put all your components in. This class becomes the 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)

Need Your Help

Double.GetHashCode algorithm or override

c# algorithm double gethashcode

i have an application project that both managed and unmanaged code runs and i need to use the same algorithm for hashing double values in both systems. so either i will override

What is the proper json encoding for the kendoui parameterMap to decode php object?

php kendo-ui json

I am having trouble passing a properly encoded json string to a php file as an object.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.