3

I need to add a simple gap/space/margin whatever to have space between these two buttons. Unfortunately I can't make it work. Could anyone give me some advice?

It's based on BorderLayout, the buttons are in a JToolBar

enter image description here

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user2061853
  • 627
  • 1
  • 7
  • 11

2 Answers2

5

What layout is on the JPanel that contains those buttons? You could use a BoxLayout and add Box.createHorizontalStrut() to it.

JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
buttonPanel.add(playButton);
buttonPanel.add(previousButton);
buttonPanel.add(Box.createHorizontalStrut(25));
buttonPanel.add(stopButton);
buttonPanel.add(Box.createHorizontalGlue());
Kevin Workman
  • 41,537
  • 9
  • 68
  • 107
  • The layout must be BorderLayout – user2061853 Mar 06 '14 at 19:45
  • Why? Are you sure the layout of the main content pane isn't the one with the BorderLayout? – Kevin Workman Mar 06 '14 at 19:48
  • No, no, use BorderLayout for the main content pane, and use BoxLayout for each component that you add to the BorderLayout. Using a BorderLayout within a BorderLayout is just odd. – Dawood ibn Kareem Mar 06 '14 at 19:49
  • Sorry, on JPanel is BorderLayout but these buttons are inside JToolBar – user2061853 Mar 06 '14 at 19:52
  • My advice is the same for a JToolBar. Try it out and ask a more specific question. – Kevin Workman Mar 06 '14 at 19:54
  • Note that you might set the layout of the tool-bar to `BoxLayout` .. I've used `FlowLayout` in a tool-bar to good effect. This is better than using a panel (added to the toolbar) with a layout for at least a few reasons. 1) The tool-bar might have a gradient paint behind it that the fixed color panel does not replicate (without `setOpaque(false)`). 2) An action can be added directly to a tool-bar, but not to a panel. 3) And of course, the toolbar will have its own, PLAF specific, separator (which is invisible on some PLAFs, and visible in others). – Andrew Thompson Mar 04 '16 at 15:11
3

See JToolBar.addSeparator() which:

Appends a separator of default size to the end of the tool bar. The default size is determined by the current look and feel.

Or JToolBar.addSeparator(Dimension) which:

Appends a separator of a specified size to the end of the tool bar.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433