Unusual spaces when using JSeperator - Java

I am working on a Swing GUI and get some unusual and unwanted spaces after adding JSeperator , any idea how to remove them? Or any other way to achieve this!

Visual description

enter image description here

Spaces are obvious before JLabel "Speed" and after JSlider .

Associated Code

 control.setLayout(new BoxLayout(control, BoxLayout.X_AXIS)); ...another code omitted... control.add(orientation); //JLabel control.add(norm); //JRadioButton control.add(back); //JRadioButton control.add(new JSeparator(SwingConstants.VERTICAL)); control.add(speedLabel); //JLabel control.add(speed); //JSlider control.add(new JSeparator(SwingConstants.VERTICAL)); control.add(turnOutLabel); //JLabel control.add(right); //JRadioButton control.add(straight); //JRadioButton control.add(left); //JRadioButton 

I want everything to be focused and shared by JSeperator,

Visual description

enter image description here

Thanks.

+6
source share
4 answers

Just replace new JSeparator(...) with the following lines (you can put them in a method if you want):

 JSeparator separator = new JSeparator(JSeparator.VERTICAL); Dimension size = new Dimension( separator.getPreferredSize().width, separator.getMaximumSize().height); separator.setMaximumSize(size); 

As @kleopatra explained, JSeparator has an unlimited maximum size (in both directions), so here you need to limit the maximum width to the preferred width, but keep the maximum height unchanged (because the preferred height is 0 ).

+7
source

The reason BoxLayout is adding these spaces is because

  • the width of your frame (panel) is larger than the overall pref sizes for children.
  • JSeparator and JSlider have unlimited (practically short. Max.) Maximum width, and all others have max. content
  • BoxLayout respects maximum sizes, so all excess is distributed between these three

The reason FlowLayout does not display delimiters at all,

  • JSeparator has a pref height of 0
  • FlowLayout gives each child its own pref size

Easy exit from Howare’s first sentence: Add full control to your dashboard with flowLayout. A more reliable solution is to switch to a more powerful LayoutManager :-)

(Editing removed again, BorderLayout.south / north - no ;-)

+4
source

change BoxLayout to the new FlowLayout (FlowLayout.LEFT). That should work. Unfortunately, I have no real explanation why BoxLayout does not work for you.

+1
source

You can put your control in another panel using FlowLayout .

Update: Unfortunately, setting control to flowlayout directly through

 control.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0)); 

does not work because the preferred separator height is zero and the separators disappear.

0
source

Source: https://habr.com/ru/post/897822/


All Articles