JMira
JMira

Reputation: 888

JFrame execution time adding JPanel

I'm working with a JFrame adding JPanel instances dynamically in the following way:

private void addBox(int x, int y){
 JPanel panel = new JPanel();
 panel.setBackground(Color.RED);
 panel.setSize(10, 10);
 panel.setVisible(true);
 panel.setLocation(x, y);
 this.getContentPane().add(panel);
}

The problem is, when I use addBox method, the JPanel instance does not appear in the JFrame. The only way I can see the box I need to manualy resize the window.

Note: I tried using this.pack();, but this did not work.

Upvotes: 2

Views: 1073

Answers (3)

mKorbel
mKorbel

Reputation: 109823

This example showing add/remove/pack may help.

private void addBox(int x, int y){
   JPanel panel = new JPanel();
   panel.setBackground(Color.RED);
   add(panel);
   //If there isn't another JPanel, then this way you'll occupy 
   //the whole JFrame area; by defalut, JFrame has BorderLayout,
   //and only one JComponent can occupy the central area 
   revalidate();
   repaint();
}

Upvotes: 1

Andrew Thompson
Andrew Thompson

Reputation: 168845

What are the purpose of the boxes?

If they are purely visual, and you don't intend to add components to them, it would be better to define a Box class (or use a Rectangle2D) and draw or fill them at time of paintComponent().

Alternately, draw them to the Graphics object of a BufferedImage and add the image to a JLabel, as shown here.

enter image description here

Upvotes: 2

aioobe
aioobe

Reputation: 421350

You need to call revalidate() and repaint() after such structural changes to the GUI.

Note that setSize and setLocation should preferrably be handled by the layout manager.

Related link:

Upvotes: 3

Related Questions