I am trying to make quite a simple layout, which would be really easy in some other layout manager. However, I need to get it working for GridBagLayout
. After a snippet of code:
GridBagConstraints c = new GridBagConstraints();
JPanel smallLogoPanel = new JPanel();
smallLogoPanel.setBorder(new LineBorder(Color.red, 1));//for visualizing components' display are
smallLogoPanel.setSize(50, 50);
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 1;
c.gridheight = 2;
c.weightx = 0.01;
c.weighty = 0.1;
c.fill = GridBagConstraints.BOTH;
JLabel smallLogoLabel = new JLabel(some code to get ImageIcon);
smallLogoPanel.add(smallLogoLabel);
this.infoPanel.add(smallLogoPanel, c);
JLabel label1 = new JLabel("Label 1");
label1.setFont(new Font("Verdana", Font.BOLD, 30));
label1.setBorder(new LineBorder(Color.red, 1));
c.gridx = 1;
c.gridy = 0;
c.gridwidth = 9;
c.gridheight = 1;
c.weightx = 0.99;//for some reason smallLogoLabel takes much more space if this weightx is any smaller
c.weighty = 0.075;
this.infoPanel.add(label1, c);
JLabel label2 = new JLabel("Label 2");
label2.setFont(new Font("Verdana", Font.BOLD, 10));
label2.setBorder(new LineBorder(Color.red, 1));
c.gridx = 1;
c.gridy = 1;
c.gridwidth = 9;
c.gridheight = 1;
c.weightx = 0.99;
c.weighty = 0.025;
this.infoPanel.add(label2, c);
... I get such a result:
... which is absolutely fine. The problem is when I add two more labels below it:
JLabel label3 = new JLabel("Label 3");
label3.setFont(new Font("Verdana", Font.BOLD, 20));
label3.setBorder(new LineBorder(Color.red, 1));
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 5;
c.gridheight = 1;
c.weightx = 0.5;
c.weighty = 0.05;
c.anchor = GridBagConstraints.CENTER;
this.infoPanel.add(label3, c);
JLabel label4 = new JLabel("Label 4");
label4.setFont(new Font("Verdana", Font.BOLD, 20));
label4.setBorder(new LineBorder(Color.red, 1));
c.gridx = 5;
c.gridy = 2;
c.gridwidth = 5;
c.gridheight = 1;
c.weightx = 0.5;
c.weighty = 0.05;
c.insets.left = 0;
this.infoPanel.add(label4, c);
...the result looks like:
Widths of top row become different, particularly panel with icon becomes wider. Another issue - bottom row. I expected both labels to be of an equal width. However, it seems the left one takes up only 1 column which is of the same width as the panel with icon.
I would be really glad I anyone could help me with this one as I am totally stuck now.