I am attempting to draw a sidebar for a project that I am working on. I chose to use GridBagLayout because I became frustrated with the limitations of BoxLayout. Could someone help explain what I am doing wrong. What I want is for the side bar to contain two JPanels. The code that I have places them halfway down the sidebar instead of at the top. Could someone explain what I am missing here.
JPanel sideBar = new JPanel();
sideBar.setBounds(0, 0, 180, (int)this.getBounds().getHeight());
sideBar.setLayout(new GridBagLayout());
JPanel optionBar = new JPanel();
optionBar.setBorder(BorderFactory.createTitledBorder("Box1"));
optionBar.setLayout(new GridBagLayout());
JPanel buttonBar = new JPanel();
buttonBar.setBorder(BorderFactory.createTitledBorder("Options"));
buttonBar.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.ipady = 5;
c.insets = new Insets(10,0,0,0);
JButton simplify;
simplify = new JButton("Open");
simplify.addActionListener( this.listener );
c.gridy = 0;
buttonBar.add(simplify, c);
JButton mergeButton;
mergeButton = new JButton("Close");
mergeButton.addActionListener( this.listener );
c.gridy = 1;
buttonBar.add(mergeButton, c);
JButton splitButton;
splitButton = new JButton("Merge");
splitButton.addActionListener( this.listener );
c.gridy = 2;
buttonBar.add(splitButton, c);
c.insets = new Insets(0,5,5,5);
c.gridy = 0;
sideBar.add(optionBar, c);
c.gridy = 1;
c.ipadx = 70;
sideBar.add(buttonBar, c);
return(sideBar);
GridBagLayout will only allocate enough vertical space that a component requires, leaving the rest blank. I expect you're seeing your side bar components centred vertically?
In order to "push" the components out, you need to set a vertical weight. If you set the weighty
constraint to 1.0 on your last component, it will take up all remaining vertical space for that component and push the rest to the top. (You may also need to anchor that last panel to GridBagConstraints.NORTH
).
Try c.weighty = 1.0
before sideBar.add(buttonBar, c);