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

Grammin picture Grammin · Jun 28, 2011 · Viewed 13.3k times · Source

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.

Answer

Penkov Vladimir picture Penkov Vladimir · Jun 28, 2011

try to use Box.createHorizontalStrut

panel.add(button1);
panel.add(Box.createHorizontalStrut(30));
panel.add(button2);
Box.createHorizontalStrut(10);
panel.add(button3);