adam
adam

Reputation: 67

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?

Upvotes: 1

Views: 2147

Answers (3)

Puce
Puce

Reputation: 38152

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)

Upvotes: 1

Anthea
Anthea

Reputation: 3809

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());
            }

        });

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 692171

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();
    }
    // ...
}

Upvotes: 1

Related Questions