6

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.

ahab
  • 61
  • 1
  • 1
  • 2
  • *"the EAST border is wider than the NORTH border"* AFAIU that is impossible. Post an [SSCCE](http://sscce.org/) that shows that. – Andrew Thompson Feb 16 '12 at 18:21

3 Answers3

7

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

Community
  • 1
  • 1
justin
  • 71
  • 1
  • 3
1

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/

alex
  • 1,229
  • 7
  • 6
0

How about reading the documentation?

http://docs.oracle.com/javase/6/docs/api/java/awt/BorderLayout.html#BorderLayout%28int,%20int%29:

Constructs a border layout with the specified gaps between components. The horizontal gap is specified by hgap and the vertical gap is specified by vgap.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255