Reputation: 67
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
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
Upvotes: 1
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
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