Java Swing: Changing border width/height on BorderLayout

ahab picture ahab · Feb 16, 2012 · Viewed 27.8k times · Source

I am a newbie to Java Swing. I am trying to make a frame containing three buttons; one in the center, another on the top, and the last one on the right. I want to make the NORTH and EAST borders the same width. But right now, the EAST border is wider than the NORTH border.

I was wondering if there was a way of changing the width of the WEST/EAST borders or the height of the NORTH/SOUTH borders, in BorderLayout.

Answer

justin picture justin · Sep 23, 2016

Assuming you are already using BorderLayout, you can use panels to control the layout of your frame and create a border feel. Then, you can request a preferred size using setPreferredSize(new Dimension(int, int)) where the (int, int) is width and height, respectively. The code for the borders would then look something like this:

JPanel jLeft = new JPanel();
JPanel jRight = new JPanel();
JPanel jTop = new JPanel();
JPanel jBottom = new JPanel();

add(jLeft, "West");
jLeft.setPreferredSize(new Dimension(40, 480));

add(jRight, "East");
jRight.setPreferredSize(new Dimension(40, 480));

add(jTop, "North");
jTop.setPreferredSize(new Dimension(640, 40));

add(jBottom, "South");
jBottom.setPreferredSize(new Dimension(640, 40));

The example above requests all borders to have the same thickness, since the width of the East and West borders matches the height of the North and South borders. This would be for a frame of size (640, 480). You can then add your buttons to the frame using something like this:

JButton button = new JButton();
jTop.add(button);
button.setPreferredSize(new Dimension(60, 20));

You can find another good example of the setPreferredSize usage here: https://stackoverflow.com/a/17027872