Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Passing a reference between different Swing components  RSS feed

 
Timmy Ryan
Ranch Hand
Posts: 63
IntelliJ IDE Java Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have a program that has a few JPanels that need to communicate. Something happens on one and another needs to get updated.
There are classes that do work in the background as well that need to update JPanels.
As there will only be ever one of each JPanel component I have made each of them a singleton.
Each component that needs a reference to the any other gets it by calling getInstance on the class required.

Is this the right way to pass these references around? Or is there some other way I should be structuring the program.
 
Haina Minawa
Ranch Hand
Posts: 119
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Timmy Ryan wrote:Hi,

I have a program that has a few JPanels that need to communicate. Something happens on one and another needs to get updated.
There are classes that do work in the background as well that need to update JPanels.
As there will only be ever one of each JPanel component I have made each of them a singleton.
Each component that needs a reference to the any other gets it by calling getInstance on the class required.

Is this the right way to pass these references around? Or is there some other way I should be structuring the program.


There is another way: event listener - components communicate with each other via a set of event methods.
 
Paul Clapham
Sheriff
Posts: 22487
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another common way to do it is to have a controller class which creates the GUI components and gives Component A a reference to Component B wherever that's necessary. So for example Component A would have a "setComponentB(ComponentB)" method. Then Component A could listen to events produced by Component B, as Haina suggests.
 
Kaveh Nickooii
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
google for "java context sensitivity". Netbeans RCP has a pretty good context sensitivity in their lookup api.

KN
 
Randall Twede
Ranch Hand
Posts: 4690
8
Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this is maybe not the same, but i have found myself needing a JPanel to get info from the JFrame. what i do is in the constructor for the JPanel i pass it a reference to "this". hope this or the other answers help.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!