Search code examples
javaswingflowlayout

How do I set the horizontal gap for just one part of a FlowLayout?


I have a flow layout with three buttons, between the first and second buttons I would like a horizontal gap of 30 and between the second and third buttons I would like a horizontal gap of 10. I tried this:

Jpanel panel = new JPanel(new FlowLayout());
JButton button1 = new Button("1");
JButton button2 = new Button("2");
JButton button3 = new Button("3");

panel.add(button1);
((FlowLayout)panel.getLayout()).setHgap(30);
panel.add(button2);
((FlowLayout)panel.getLayout()).setHgap(10);
panel.add(button3);

But this changes all of the Horizontal gaps to 10.

Any ideas would be appreciated, Thanks.


Solution

  • Add an EmptyBorder to the 2nd button, with the additional pixels in the second parameter (left):

    button2.setBorder(new EmptyBorder(0, 20, 0, 0));