Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Why my JPanel doesn't show in JFrame

public class Sample7 { private JFrame f; private JPanel p; private JButton b1; private JLabel lab;

public static void main(String args[]) { new Sample7(); }

public Sample7() { gui(); }

public void gui() { f = new JFrame("Creativity tuts"); f.setVisible(true); f.setSize(600,1200); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

p=new JPanel();
p.setBackground(java.awt.Color.RED);

b1=new JButton("Test");
lab =new JLabel("This is test label");

p.add(b1);
p.add(lab);

} }

2 Answers

make sure that the JFrame adds the panel. After your panel adds all of the items then add your panel to your JFrame. Like this:

JPanel panel = new JPanel();
panel.add(someStuff);
panel.add(someMoreStuff);

JFrame frame = new JFrame();
frame.add(panel);

Or you could do it this way:

import javax.swing.JPanel;

public class MyPanel extends JPanel {
  //some code goes here
}
//****************************************************
import javax.swing.JFrame;

public class runPanel{

   public static void main(String[] args){

      JFrame frame = new JFrame();

      MyPanel myPanel = new MyPanel();

      frame.add(myPanel);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
      frame.setSize(500, 500);

   }

}