Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a "Group Box" equivalent in Java Swing?

Trying to build a GUI application in Java/Swing. I'm mainly used to "painting" GUIs on the Windows side with tools like VB (or to be more precise, Gupta SQLWindows... wonder how many people know what that is ;-)).

I can't find an equivalent of a Group Box in Swing...

With a group box, you have a square box (usually with a title) around a couple of related widgets. One example is a group box around a few radio buttons (with the title explaining what the radio buttons are about, e.g. Group Box entitled "Sex" with "Male" and "Female" radio buttons).

I've searched around a bit... the only way I found was to add a sub-pane, set the border on the sub-pane and then add all the widgets in the "group" to the sub-pane. Is there a more elegant way to do that?

like image 888
Thorsten Avatar asked Jan 10 '09 20:01

Thorsten


People also ask

Is Swing still used in Java 2021?

Absolutely yes. Legacy swing applications are still supported and enhanced.

What has replaced Java Swing?

JavaFX was intended to replace Swing as the standard GUI library for Java SE, but it has been dropped from new Standard Editions while Swing and AWT remain included, supposedly because JavaFX's marketshare has been "eroded by the rise of 'mobile first' and 'web first applications."


2 Answers

Create a JPanel, and add your radiobuttons to it. Don't forget to set the layout of the JPanel to something appropriate.

Then call panel.setBorder(BorderFactory.createTitledBorder(name));

like image 163
David Koelle Avatar answered Oct 13 '22 18:10

David Koelle


Others have already commetned about JPanel and using a TitledBorder, that's fine.

However, when playing with Swing LayoutManagers, you may find it annoying that components in different JPanels cannot align correctly (each panel has its own LayoutManager).

For this reason, it is a good practice (check "JGoodies" on the web for more details) in Swing GUIs to NOT use TitledBorders but rather separate groups of components in a JPanel by a JLabel followed by a horizontal JSeparator.

Ref. "First Aid for Swing"

like image 24
jfpoilpret Avatar answered Oct 13 '22 18:10

jfpoilpret