Skip to main content

JFrame and JPanel

4 replies [Last post]
atdc12
Offline
Joined: 2004-10-11

Hi all,

I have a JPanel inside a JFrame. I want my JPanel to be able to invoke some method that I create on my JFrame, and vice versa.

What is the best way to do it, besides passing the JFrame instance to the JPanel's constructor ?

Thanks.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
insider
Offline
Joined: 2003-10-26

Why not to set panel as a field to your Frame class

public class MyFrame extends JFrame {
private JPanel myPanel;

public MyFrame() {
// myPanel = new ...
add(myPanel);
}
}

this way myPanel is visible everywhere inside MyFrame and vice versa

Alex

atdc12
Offline
Joined: 2004-10-11

Thanks for the responses, everybody.

BTW, Can I ask for your suggestion. My classes structure is like this :

+JFrame
+---JPanel1
+------Class1
+---JPanel2

Class1 (which reside inside JPanel1) needs to be able to call some methods from JPanel2, how can I do that? Should I have a reference to JPanel2 in Class1, or is there any other suggestion?

Thanks.

leouser
Offline
Joined: 2005-12-12

there are many ways to do it. The bad but doable way is to get the JFrame, from that get the children, get the right child and do the manipulation.

another idea is:

MotherClass
-JFrame
--JPanel1
---Class
--JPanel2

have the mother class accessible to Class and have the JPanel2 grabbable or at least have a method that can send it message from the MotherClass...

There are many ways of doing this, go with the one that works with your design.

leouser
Offline
Joined: 2005-12-12

try: getTopLevelAncestor()
Returns the top-level ancestor of this component (either the containing Window or Applet), or null if this component has not been added to any container.

This may be the ticket for what your after...