It is often necessary to change the behaviour of other GUI objects depending on the state of another GUI object. E.g. when a button is pressed, a label shall change its name. However, when I use an AbstractAction object like JButton myButton = new JButton(myButtonAction); I need a reference to the GUI objects in the object that inherits from AbstractAction. Should I just create the AbstractAction objects in the GUI and then pass all the necessary GUI references to the AbstractAction objects or could that be considered bad style?
To make it more concrete:
// AbstractAction
public class MyAction extends AbstractAction {
public MyAction(String name,
String description, Integer mnemonic, JLabel) {
super(name);
putValue(SHORT_DESCRIPTION, description);
putValue(MNEMONIC_KEY, mnemonic);
}
public void actionPerformed(ActionEvent e) {
// do something
}
}
}
public class GUI{
public Action myAction = null;
public GUI(){
JLabel label = new JLabel("text");
//This is not a good idea:
myAction = new MyAction("some text" , desc, new Integer(KeyEvent.VK_Q), label);
JButton myButton = new JButton(myAction);
}
}
You want to loosen coupling as much as possible, not tighten it as your question suggests, and to do this, I think that you should do further abstraction, by separating portions even further into a full-fledged MVC program. Then the listener (the Action) can change the model, and the view, which is your GUI, can listen for model's changes and respond accordingly.
For example:
The key in my mind is that the Model knows nothing of the view, and the view knows little (here nothing) about the model.