Search code examples
javaswingjbuttonspacingflowlayout

Java Swing: How to remove the default-spacing for JButtons in a JPanel


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?


Solution

  • // 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!