Java Swing: Changing border width/height on BorderLayout

30,052

Solution 1

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

Solution 2

As far as I know, you cannot directly set the height/width of the Border areas. You can only specify the size of the components you place within those areas.

But, as already mentioned, you can specify the gap between the areas.

GridBagLayout is more flexible, but also more complicated.

Building Layouts in Swing is not always easy - maybe using MigLayout (a third party library) would simplify things for you: http://www.miglayout.com/

Share:
30,052
ahab
Author by

ahab

Updated on July 24, 2022

Comments

  • ahab
    ahab over 1 year

    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.