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
GridBagLayout is one of the most flexible — and complex — layout managers the Java platform provides. A GridBagLayout places components in a grid of rows and columns, allowing specified components to span multiple rows or columns. Not all rows necessarily have the same height.
weightx and weighty are used to determine how to distribute space among columns and among rows. This values are important for specifying resizing behavior. If you do not specify any of weightx or weighty, all the components will clump together in the center of their container.
The GridBagLayout class is a flexible layout manager that aligns components vertically, horizontally or along their baseline without requiring that the components be of the same size.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With