Reputation: 888
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
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
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.
Upvotes: 2
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