0

I have a main class which extends JFrame, and its content is contained in other classes which extend JPanel.

Now, in those other classes, I want to use several panels to group the content in a good order.

Is it possible to use many panels( by creating several JPanel objects in that class) in this class that extends JPanel?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
gthuo
  • 2,376
  • 5
  • 23
  • 30

1 Answers1

1

JPanel extends JComponent, which extends Container, so JPanel is a container, so it contain other Component.

So, yes, you can do this and in fact, depending on the context and requirements, is actually a good idea.

You could take a look at this example and this example

mKorbel makes a valid point. It is generally not recommended to extend from top level containers like JFrame, instead, use something like JPanel as you primary application interface (adding other containers and components to it as you see fit) and adding this frame to an instance of JFrame which you create

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Edit: the other classes extend JPanel, not JFrame – gthuo Oct 09 '13 at 06:50
  • @GThuo That did have me worried ;) – MadProgrammer Oct 09 '13 at 06:50
  • This exactly is my problem: Lets say I have this class `MainPage` `public class MainPage extends JPanel { public MainPage() { //create 2 buttons JButton actAddUser = new JButton("Add User"); JButton actAddBook = new JButton("Add Book"); //add this buttons to this panel add(actAddUser); add(actAddBook); //now create a text field JTextField text = new JTextField(); //now i want to add this to a different panel //something like JPanel panel2 = new JPanel(); panel2.add(text);` Is this allowable, because it is throwing an exception of adding window to container? – gthuo Oct 09 '13 at 09:22
  • Yes it's allowed, some where in your class hierarchy, some is extending from a window based class – MadProgrammer Oct 09 '13 at 09:28
  • thank you. My problem is not sorted. On top of your suggestion, I stopped extending the classes with `JPanel` – gthuo Oct 09 '13 at 10:06