How to draw a separator across a panel (GridBagLayout)

1.9k Views Asked by At

I am trying to add a JSeparator across a Panel in GridBagLayout, but it's not showing up.

I tried options like

panel.add(new JSeparator());

and

panel.add(new JSeparator(SwingConstants.HORIZONTAL));

None of them are giving a visible separator.

1

There are 1 best solutions below

0
On

Read the section from the Swing tutorial on How to Use Separators where you will find the statement:

Separators have almost no API and are extremely easy to use as long as you keep one thing in mind: In most implementations, a vertical separator has a preferred height of 0, and a horizontal separator has a preferred width of 0. This means a separator is not visible unless you either set its preferred size or put it in under the control of a layout manager such as BorderLayout or BoxLayout that stretches it to fill its available display area.

So if you use it with a GridBagLayout, then you will need to specify proper constraints so that the separator fills all the columns for the given row. Read the section from the Swing tutorial on How to Use GridBagLayout for more information on the constraints and working examples. The tutorial demonstrates how to have a button fill 3 columns, so try replacing the button with your separator.