我用4個JPanel創建了一個JFrame。使用GridBagLayout,我創建了三行兩列,每列兩個面板。通過將藍色面板的cellheight從1更改爲2,我可以覆蓋它下面的單元格。我想爲綠色面板做同樣的事情,以填充它下面的空間。下面是我的代碼目前生產:GridBagLayout - 我如何讓這個單元格填充它下面的空間?
我試圖改變綠色面板的gridheight爲2,但我結束了這一點:
我使用的GridBagLayout不正確?這樣做的適當方式是什麼?
這裏是我的代碼:
import java.awt.Color;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
addComponents(frame.getContentPane());
frame.setSize(800, 600);
frame.setVisible(true);
}
public static void addComponents(Container contentPane) {
contentPane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(3,3,3,3);
c.fill = GridBagConstraints.BOTH;
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 1;
c.gridheight = 2;
c.weightx = 1;
c.weighty = 0.85;
JPanel panel1 = new JPanel();
panel1.setBackground(Color.BLUE);
contentPane.add(panel1, c);
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = 1.1;
c.weighty = 0.35;
JPanel panel2 = new JPanel();
panel2.setBackground(Color.YELLOW);
contentPane.add(panel2, c);
c.gridx = 1;
c.gridy = 0;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = 0.15;
c.weighty = 0.5;
JPanel panel3 = new JPanel();
panel3.setBackground(Color.RED);
contentPane.add(panel3, c);
c.gridx = 1;
c.gridy = 1;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = 0.38;
c.weighty = 0.5;
JPanel panel4 = new JPanel();
panel4.setBackground(Color.GREEN);
contentPane.add(panel4, c);
}
}
行跨度爲更好地幫助越早第三列如預期發佈[MCVE ]或[簡短,獨立,正確的例子](http://www.sscce.org/)。 –
謝謝安德魯。我添加了其餘的代碼。 –
注意:如果有三個單元格的第三列,每個單元格的行跨距爲1,它就會像預期那樣工作。 –