I read a lot about this problem here... But I just don't seem to get how to solve this. All the solutions I tried are not working.
But let's start at the beginning: I'm building my interface with Swing and trying to be modular. So I've got a class (extending JPanel) for my left Main Menu. The Menu is built with several buttons in a GridBagLayout.
But I am not able to get this layout to aligned to the top of the window (panel). Example: Label at the Top of the Panel, Text Field below, button below the text field, etc.
Please see my code:
public class LeftMenu extends JPanel {
public LeftMenu(){
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[] { 86, 0 };
gbl_panel.rowHeights = new int[] {32, 32, 32, 32, 32, 32, 32, 32, 32 };
gbl_panel.columnWeights = new double[] { 0.0, Double.MIN_VALUE };
gbl_panel.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0 };
setLayout(gbl_panel);
JLabel lblEnterTrunkId = new JLabel("Enter Trunk ID");
GridBagConstraints gbc_lblEnterTrunkId = new GridBagConstraints();
gbc_lblEnterTrunkId.fill = GridBagConstraints.HORIZONTAL;
gbc_lblEnterTrunkId.insets = new Insets(0, 0, 5, 0);
gbc_lblEnterTrunkId.gridx = 0;
gbc_lblEnterTrunkId.gridy = 0;
gbc_lblEnterTrunkId.anchor = GridBagConstraints.NORTH;
add(lblEnterTrunkId, gbc_lblEnterTrunkId);
}
}
There is a text field and some buttons following behind the Label. But I assume, these are not relevant... If they are... they are mostly looking like the Label (just that they are not Labels... I think you get me)
All guides I read, are all pointing to the anchor of the GridBagConstraint. It is there.... but not working. It's wonderfully aligned in the middle of the panel.
If it does matter: the Panel ist used as a LeftComponent of a SplitPane:
public LeftMenu leftpanel = new LeftMenu();
splitPaneTrunks.setLeftComponent(leftpanel);
Looking forward to your help.
Here is a picture of my side menu... centered horizontally. as it should not be.
Instead of using GridBagLayout
, you could make a wrap using a JPanel
with the layout BorderLayout
, like so:
setLayout(new BorderLayout());
JPanel gridBagWrap = new JPanel();
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[] { 86, 0 };
gbl_panel.rowHeights = new int[] {32, 32, 32, 32, 32, 32, 32, 32, 32 };
gbl_panel.columnWeights = new double[] { 0.0, Double.MIN_VALUE };
gbl_panel.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0 };
gridBagWrap.setLayout(gbl_panel);
JLabel lblEnterTrunkId = new JLabel("Enter Trunk ID");
GridBagConstraints gbc_lblEnterTrunkId = new GridBagConstraints();
gbc_lblEnterTrunkId.fill = GridBagConstraints.HORIZONTAL;
gbc_lblEnterTrunkId.insets = new Insets(0, 0, 5, 0);
gbc_lblEnterTrunkId.gridx = 0;
gbc_lblEnterTrunkId.gridy = 0;
gbc_lblEnterTrunkId.anchor = GridBagConstraints.NORTH;
gridBagWrap.add(lblEnterTrunkId, gbc_lblEnterTrunkId);
add(gridBagWrap, BorderLayout.NORTH);