1

Hi I have been learning Java Swing for creating a chess game to practice my Java programming skills.

I've added a JPanel to the east of the JFrame with BorderLayout and I've used the setPrefferedSize(new Dimension(x,y)) method to set the width and height.

After that I have created 4 JPanel and added them with BoxLayout on the previously created panel.

I have tried to set the size of the 4 panels with the setSize(x,y) and setPreferredSize(new Dimension(x,y)) but it dosent work the 4 panels automaticly changed there size to fit the main JPanel and after adding a JLabel on one of them the size of it increased automaticly .

This is my code:

this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
JPanel a = new JPanel(); 
a.setPreferredSize(new Dimension(50, 50)); //this dosent work
a.add(min);
a.setBackground(Color.red);
this.add;

JPanel b = new JPanel();   
b.setBackground(Color.blue);
this.add(b);

JPanel c = new JPanel(); 

this.add(c);

JPanel d = new JPanel();
d.setBackground(Color.black);
this.add(d);

How can I change the size of each of these panels?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
user1146440
  • 363
  • 1
  • 9
  • 19
  • These issues you are dealing with are layout dependant. Is it mandatory that use use `BoxLayout`? For me, personally, I would use `GridLayout` for the task you're trying to accomplish. – fireshadow52 Jan 23 '12 at 20:42
  • 2
    See also this [example](http://stackoverflow.com/a/2562685/230513) and [variation](http://stackoverflow.com/a/2563350/230513); more [here](http://stackoverflow.com/questions/7229226/should-i-avoid-the-use-of-setpreferredmaximumminimumsize-methods-in-java-swi/7229662). – trashgod Jan 23 '12 at 21:01
  • Those are indeed `BoxLayout` issues. try using `Grid` layout, and it will be far more what you are expecting. – Sheriff Jan 23 '12 at 21:59

1 Answers1

3

BoxLayout is best for laying out components with varying sizes along a single axis. From the Javadocs:

"BoxLayout attempts to arrange components at their preferred widths (for horizontal layout) or heights (for vertical layout)."

The idea is that they may have different heights (for a horizontal layout) and it will take the maximum height. And, they definitely may have different widths. Also, BoxLayout works with some, er, "interesting" filler pieces like Box.createHorizontalGlue(). These are actually quite useful for flexible, resizeable layouts once you get the hang of it. But, all in all, BoxLayout is for flexible, resizable layout of items with differing sizes.

For simpler cases, especially if you want both preferred width and preferred height to be "respected", use GridLayout as everybody else has suggested.

user949300
  • 15,364
  • 7
  • 35
  • 66