问题
I have been working on a Swing GUI and getting some unusual and unwanted gaps after adding JSeperator
, Any idea how to remove them? Or any other option to how to achieve this nicely!
Visual Description
Gaps are apparent before JLabel
"Speed" and after JSlider
.
Related 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
What I want is to Have have everything centred and separated by JSeperator,
Visual Description
Thank you.
回答1:
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
).
回答2:
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 ;-)
回答3:
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.
回答4:
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.
来源:https://stackoverflow.com/questions/7515241/unusual-gaps-while-using-jseperator-java