views:

239

answers:

3

I want to add a vertical JSeparator between two components using a GridBagLayout. The code I have is as follows:

public MainWindowBody(){
    setLayout(new GridBagLayout());

    JPanel leftPanel = new InformationPanel();
    JPanel rightPanel = new GameSelectionPanel();

    JSeparator sep = new JSeparator(JSeparator.VERTICAL);
    GridBagConstraints gbc = new GridBagConstraints();

    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.anchor = GridBagConstraints.NORTH;

    add(leftPanel,gbc);

    gbc.gridx = 1;
    gbc.gridy = 0;
    gbc.fill = GridBagConstraints.VERTICAL;

    add(sep,gbc);

    gbc.gridx = 2;
    gbc.gridy = 0;
    gbc.fill = GridBagConstraints.NONE;

    add(rightPanel,gbc);
}

But the JSeperator doesn't show, any ideas?

Thanks

A: 

You should add the constraints to the layout before adding the components to the parent:

GridBagLayout gb = new GridBagLayout()
setLayout(gb);

gbc.gridwidth = GridBagConstraints.RELATIVE;
gbc.anchor = GridBagConstraints.NORTH;

// don't do add(leftPanel,gbc); but do:
gb.setConstraints(leftPanel, gbc);
add(gbc);

gbc.fill = GridBagConstraints.VERTICAL;

gb.setConstraints(sep, gbc);
add(sep);

gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.NONE;

gb.setConstraints(rightPanel, gbc);
add(rightPanel);
Thomas
that does not solve the problem. Also what benefits does this have over add(comp, constraints)?
Aly
+1  A: 

Taken from Sun's guide for JSeparator:

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.

The vertical separator does have a bit of width (and the horizontal a bit of height), so you should see some space where the separator is. However, the actual dividing line isn't drawn unless the width and height are both non-zero.

Maybe you should set right constraints?

Jack
is there any way under the grid bag layout i can make it stretch to the height of the window?
Aly
@Aly, set gbc.weighty = 1;
Thomas
+1  A: 

You could try to set the preferred width for the separator:

sep.setPreferredSize(new Dimension(5,1));

Then, make GridBagLayout use up all available height for the separator:

gbc.fill = GridBagConstraints.VERTICAL;
gbc.weighty = 1;
Thomas