user1146440
user1146440

Reputation: 363

Java Swing Panel Size

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?

Upvotes: 1

Views: 5265

Answers (1)

user949300
user949300

Reputation: 15729

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.

Upvotes: 3

Related Questions