Multiple GridBag Alignments JPanelConstraints

enter image description here

As shown in the figure, first there are two panels: topPanel and btmPanel. TopPanel consists of two more panels, one of which is filled with black and one filled with gray is not a problem.

There are three panels in btmPanel which are in GridbagLayouts, each panel has a different number of JButtons. The problem is that the third panel has more JButtons, so I want them to align them to start from the top. Is it possible?

Thanks.

+4
source share
2 answers

When setting the limits of these 3 panels, make sure that

  • set the GridBagConstraint weighty property for something greater than 0, like 1.0,
  • and set the anchor property to NORTH or NORTHEAST or NORTHWEST .

Of course, the fill property can only be set to NONE or HORIZONTAL , otherwise all panels will be stretched vertically, which, I think, you do not need.

Here is an example of what I am describing. I simplified your case by replacing 3 large panels with 3 buttons (one of them is higher than the other):

Results (see how 3 buttons are aligned on top):

enter image description here

 import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; public class TestLayout { protected void initUI() { final JFrame frame = new JFrame(TestLayout.class.getSimpleName()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel btmPanel = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.weighty = 1.0; gbc.weightx = 1.0; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.insets = new Insets(5, 5, 5, 5); gbc.anchor = GridBagConstraints.NORTH; JButton comp = new JButton("Panel-1"); btmPanel.add(comp, gbc); JButton comp2 = new JButton("Panel-2"); btmPanel.add(comp2, gbc); JButton comp3 = new JButton("Panel-3"); comp3.setPreferredSize(new Dimension(comp.getPreferredSize().width, comp.getPreferredSize().height + 10)); btmPanel.add(comp3, gbc); frame.add(btmPanel); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new TestLayout().initUI(); } }); } } 
+2
source

Just set the layout for btmPanel to GridLayout (1, 3, 5, 5); that will line them on top. Since the default layout for btmPanel is currently FlowLayout, so you are experiencing this problem. At the top of this btmPanel you have these three GridBagLayout with a GridBagLayout .

+1
source

Source: https://habr.com/ru/post/1438919/


All Articles