Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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: Layouts with Insets, instead of separators.)

like image 543
Warren P Avatar asked Jun 04 '10 15:06

Warren P


People also ask

How to add space between components in Java?

JSeparator is meant to be a visible separator between components. 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() .

What is JPanel Swing Java?

The JPanel is a simplest container class. It provides space in which an application can attach any other component. It inherits the JComponents class. It doesn't have title bar.


2 Answers

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.

like image 197
Adamski Avatar answered Sep 23 '22 15:09

Adamski


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().

like image 38
jjnguy Avatar answered Sep 22 '22 15:09

jjnguy