Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
    Bookmark Topic Watch Topic
  • New Topic

JPanel Visible Answer

 
Glen Tanner
Ranch Hand
Posts: 147
Java Python Ruby
  • Mark post as helpful
  • send pies
  • Report post to moderator
code:


package BouncingBalls;

import java.awt.*;
import javax.swing.*;

public class Main {

public static void main(String[] args) {

JPanel p = new JPanel();
p.setPreferredSize(new Dimension(400, 400));
p.setVisible(true);

}

}




Simply, why the JPanel is not visible when running this. Nothing appears and there are no errors.

Thanks



ANSWER:

import java.awt.*;
import javax.swing.*;

public class Main {

public static void main(String[] args) {

JFrame f = new JFrame("My Frame");
f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);

JPanel p = new JPanel();
p.setPreferredSize(new Dimension(400, 400));

f.getContentPane().add(p);
f.pack();
f.setVisible(true);

}

}
 
Glen Tanner
Ranch Hand
Posts: 147
Java Python Ruby
  • Mark post as helpful
  • send pies
  • Report post to moderator
Sorry, the other thread was closed so I started another...

Short answer is that you have to add the JPanel to a top level container.

http://java.sun.com/docs/books/tutorial/uiswing/components/toplevel.html
 
Campbell Ritchie
Sheriff
Posts: 48910
58
  • Mark post as helpful
  • send pies
  • Report post to moderator
No, your other thread wasn't closed. It was moved.

This one is closed however.
 
Campbell Ritchie
Sheriff
Posts: 48910
58
  • Mark post as helpful
  • send pies
  • Report post to moderator
I must apologise; I thought at first you were the original poster.

You must have been trying to post at the same time as I moved the original thread, so it would have refused the reply. Although your reply was helpful, I can't drag the thread back from the Swing forum.

So this thread will have to stay closed, but I am sorry for messing you about, and would like to make you welcome here at JavaRanch.
 
    Bookmark Topic Watch Topic
  • New Topic