2

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.

mrkhrts
  • 829
  • 7
  • 17
JMira
  • 888
  • 4
  • 16
  • 34

3 Answers3

3

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:

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • How I should use the layout manager to handled the size and location? – JMira Sep 15 '11 at 13:23
  • That depends on how you want the components to be layed out in the frame. If you want the box to have position `x,y` you should create a custom layout manager, set the content pane to use this manager, and pass x and y to the layout manager when adding the panel. Google for *java custom layout manager* for instance. – aioobe Sep 15 '11 at 13:29
2

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

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
1

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();
}
Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • how do you know he hasn't done `getContentPane().setLayout(null)`? – aioobe Sep 15 '11 at 13:28
  • @aioobe 1) yes only in case that there is `setLayout(null)`, 2) no for `setSize` and `setLocation`, because pretty ignored used LayoutManager and works in all cases – mKorbel Sep 15 '11 at 13:40
  • *...and works in all cases* -- Uhm, the values passed to `setSize` will be overridden by any layout-manager present (i.e. will only be in use until the component needs to be "re-layed-out"). Perhaps that's what you tried to say ;-) – aioobe Sep 15 '11 at 13:52