Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Accessing methods in different classes

Status
Not open for further replies.

MavenHades

Programmer
Dec 21, 2008
9
US
I am working on a Java Swing application. I have a JFrame that contains multiple panels. Each of these panels are their own class that extends JPanel. So I have a button on one panel and a text field on another panel. Once the button is clicked, I want to change the text in the text field. What is the best way to update the text field?
If I create a method called "setText(String text)" how would I access it from the button panel? I do not want to pass the button panel to the text field panel's constructor as they have to communicate with other panels as well. This would get cumbersome when you have five panels to pass. However this is the only way I know how to access methods of other classes, but are there any other possible methods of communication? Thanks.
 
For each panel I would store it's parent (the JFrame that contains all the panels).

This way a button in a panel could call a method in the parent JFrame, and the JFrame should be able to update a field in any of its panels.
 
Thanks for the replies. Is passing the parent (JFrame in my case) the normal design pattern used?
 
Don't know if it's a common patern, but passing the parent in the constructor it's the way I do it when I need to.
 
You don't need to store the parent, you have the getParent method for that.

Cheers,
Dian
 
Yes, let the main container (JFrame in this case) be the traffic cop. It gets and routes all the actions to the appropriate place. If you don't want to ref the JFrame in the panels, the Jframe can be made the ActionListener (which gets messy when lots of buttons are involved), or the JFrame can contain the ActionListeners.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top