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 difficulty 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
JFrame1when constructionJPanel1:and remember and use that in JPanel1:
But that’s bad.
Instead, think about what clicking A really means (for example pauze game). Then create a
PauzeGameEventListenerinterface, implemented by JPanel2 (for example the chessboard) and make JPanel1 (for example the game controls panel) fire aPauzeGameEventto 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.