开发者

What is the best way to put spaces between objects? Can a Swing JSeparator object be an invisible separator?

开发者 https://www.devze.com 2023-01-02 01:59 出处:网络
I\'m trying to put two buttons inside a panel using Swing widgets. Inside the NetBeans IDE, my JSeparator border property is set to (No border) in the properties pane.

I'm trying to put two buttons inside a panel using Swing widgets. Inside the NetBeans IDE, my JSeparator border property is set to (No border) in the properties pane.

Nevertheless a line appears. This is not what I would expect from a separator object. Am I doing something wrong? Coming from a background in Delphi, and C# WinForms, I expect to find some oddities in Swing. But how exactly do you make a transparent gap of a particular size, between two buttons in a panel? Do I have to play with layouts and avoid the JSeparator?

Update: It should be trivial to do this with a layout and without any separator object. So how do you do that? I am looking into the NetBeans layout customizer and properties inspector and finding no way to do it. (Answer: La开发者_运维知识库youts with Insets, instead of separators.)


You should take a look at the static utility methods on the Box class. They can be used to manufacture fixed struts that act as invisible separators; e.g.

JPanel pnl = new JPanel(new FlowLayout());
pnl.add(new JButton("Hello"));
pnl.add(Box.createHorizontalStrut(10)); // Fixed width invisible separator.
pnl.add(new JButton("Goodbye");

This produces more compact code than creating / configuring a JPanel yourself with appropriate minimum, maximum and preferred dimensions.


JSeparator is meant to be a visible separator between components.

From the javadoc for JSeparator:

JSeparator provides a general purpose component for implementing divider lines - most commonly used as a divider between menu items that breaks them up into logical groupings.

If you want to put a component in between two components that is invisible just use an JPanel instead. Then set the size of the panel with setPreferedSize() and setMin/MaxSize().


You don't need JSeparator. Most layouts allow you to set gap (space) between compoponents. And Box class can be particularly useful.


Using addSeparator with a value of 1 for height makes it invisible for me, for example:

MyJToolBar.addSeparator(new Dimension(20, 1));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号