Java - calling a method of an object not in scope (parent's children)
This may have been asked many times before or I don't know what to search for to get an answer. What I have got is a JFrame that loads in several JPanels. What I am having diffic开发者_运维问答ulty in is updating the contents of one JPanel from another. So say I have the following:
JFrame1.JPanel1.JButtonA
JFrame1.JPanel2.JButtonB
When JButtonA is pressed I want JButtonB to have its text changed. Of course this isn't what I want to do but is a simple example of what I would like to achieve. Where am I going wrong? How to get a reference to an object without making everything a singleton?
The easiest way is of course to remember a reference to JFrame1
when construction JPanel1
:
JPanel1 p1 = new JPanel1(this);
and remember and use that in JPanel1:
public JPanel1(JFrame1 f1) {
this.f1 = f1;
}
...
public void actionPerformend(...) {
f1.getPanel2().getButtonB().setText("A is pressed");
}
But that's bad.
Instead, think about what clicking A really means (for example pauze game). Then create a PauzeGameEventListener
interface, implemented by JPanel2 (for example the chessboard) and make JPanel1 (for example the game controls panel) fire a PauzeGameEvent
to all listeners. That way, when your JPanel3 (for example score panel) or non-gui stuff (for example the AI player) needs to be aware of that too, you're not littering the JPanel1 code.
精彩评论