Unusual gaps while using JSeperator - Java

六月ゝ 毕业季﹏ 提交于 2019-12-04 06:40:59

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 unbounded maximum size (in both directions), so the trick here is to limit the max width to the preferred width, but still keep the max height unchanged (because the preferred height is 0).

The reason BoxLayout is adding those gaps is that

  • the width of your frame (panel) is greater than the total pref sizes of the children
  • JSeparator and JSlider have an unbounded (practically, it's Short.Max) max width while all others have a content dependent max
  • BoxLayout respects max sizes, so all excess gets distributed between those three

The reason FlowLayout doesn't show the separators at all,

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

The easy way out is Howare's first suggestion: add the complete control to a panel with flowLayout. The more robust solution is to switch over to a more powerful LayoutManager :-)

(removed edit again, BorderLayout.south/north doesn't ;-)

change BoxLayout to new FlowLayout(FlowLayout.LEFT). This should work. Unfortunately I do not have a real explanation why BoxLayout does not work for you.

You may put your control into another panel with a FlowLayout.

Update: Unfortunately setting the control to flowlayout directly via

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

does not work, since the separator's preferred height is zero and the separators will disappear.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!