Search code examples
javaswinglistenerjcomboboxjtextfield

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?


Solution

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