2

I'm busy writing a button menu for a Java Swing application and I am wondering if it is possible to remove the padding between JButtons that are added to a JPanel.

The JPanel uses a FlowLayout that is aligned left.

JPanel panelMenu = new JPanel(new FlowLayout(FlowLayout.LEFT));

The buttons are standard JButtons

JButton buttOne = new JButton("One");
JButton buttTwo = new JButton("Two");

I added the JButtons to the panel as normal

add(panelMenu, BorderLayout.NORTH);
panelMenu.add(buttOne);
panelMenu.add(buttTwo);

Everything works as expected but what do I need to do to remove the default spacing between the buttons?

I found a suggested solution online which is the following

buttOne.setBorder(null);
buttOne.setBorderPainted(false);
buttOne.setMargin(new Insets(0,0,0,0));

buttTwo.setBorder(null);
buttTwo.setBorderPainted(false);
buttTwo.setMargin(new Insets(0,0,0,0));

However this seems to remove the spacing inside of the button and not the spacing between each button.

Is this spacing produced by the FlowLayout? If so, how can I remove it?

2 Answers 2

7

// 0, 0 equates to horizontal and vertical offsets, the default is 5.

JPanel panelMenu = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));

Should sort it!

0
3

The FlowLayout controls the spacing, the default is 5.
Use new FlowLayout(FlowLayout.LEFT, 0) to remove the spacing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.