Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Multiple JFrames in 1 Container

 
Timothy Sam
Ranch Hand
Posts: 751
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, is this advisable? I was trying to create multiple windows with JFrame with only one instance of the Container class. I do it like this...

JFrame window1 = new JFrame("Window 1");
JFrame window2 = new JFrame("Window 2");

Container container = window1.getContentPane();
container.setLayout(new FlowLayout());

window1.setSize(200, 100);
window1.setVisible(true);

window2.setSize(200, 100);
window2.setVisible(200, 100);

I've tried this and it worked. I didn't paste the whole code because I'm typing on my mac and surfing the internet through PC. I'd just like to ask if it's ok to do this practice? Or is ther something I should avoid in doing this? Thanks!
 
Stephen Boston
Ranch Hand
Posts: 165
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hmmm... I'd like to see what happens when you try to add components to the second JFrame.
 
Stephen Boston
Ranch Hand
Posts: 165
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So, I tried it.



Compiles just fine, but running it....


Exception in thread "main" java.lang.Error: Do not use javax.swing.JFrame.add()
use javax.swing.JFrame.getContentPane().add() instead
at javax.swing.JFrame.createRootPaneException(JFrame.java:465)
at javax.swing.JFrame.addImpl(JFrame.java:491)
at java.awt.Container.add(Container.java:307)
at Testing.<init>(Testing.java:16)
at Testing.main(Testing.java:27)

So I'm thinking you can't use your container for both windows without some fancy foot work.

And this example won't compile.

Compile error: container is already defined in Testing()

BUT! You can do this.


Thanks! That was fun!
[ October 12, 2005: Message edited by: Stephen Boston ]
 
cat cater
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Multiple JFrames in 1 Container ? why don't use JDesktop and JInternalFrame?
code:
-------------
JPanel pt=new JPanel(new BorderLayout());
JDesktop desk = new JDesktop();
JInternalFrame inner1 = new JInternalFrame();
JInternalFrame inner2 = new JInternalFrame();
JInternalFrame inner3 = new JInternalFrame();
pt.add(desk);
desk.add(inner1);
desk.add(inner2);
desk.add(inner3);
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic