我有3个JPanels,我想将它们全部放在一个JPanel中。我使用GridBagLayout作为主面板。但是只添加了一个面板。为什么会这样?
gblayout=new GridBagLayout();
gbc=new GridBagConstraints();
panel1Customizer();
panel2customizer();
panel3Customizer();
setLayout(gblayout);
gbc.fill=GridBagConstraints.HORIZONTAL;
gbc.anchor=GridBagConstraints.NORTHWEST;
gbc.weightx=1;
gbc.weighty=1;
gbc.gridheight=GridBagConstraints.REMAINDER;
add(panel1, gbc);
add(panel2, gbc);
gbc.gridwidth=GridBagConstraints.REMAINDER;
add(panel3, gbc);
自定义程序方法是将项目添加到这些面板中的方法。
答案 0 :(得分:1)
我不确定,但我认为您需要在GridBagLayout中添加GridBagConstraints。试试看这个网站,了解如何使用GridBagLayout: link
或者也许只是为你的JFrame使用另一个布局,可能是BorderLayout或GridLayout来正确排列你的面板
答案 1 :(得分:1)
您应该为每个面板更改gbc.gridx和/或gbc.gridy
答案 2 :(得分:1)
您必须阅读How to Use GridBagLayout,here和GridBagConstraints的示例,如果您遇到gbc.fill=GridBagConstraints.HORIZONTAL;
问题,请更改JComponent's Size
添加setPreferedSize()
;例如
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
public class GBLFillBoth extends JFrame {
private static final long serialVersionUID = 1L;
public GBLFillBoth() {
JPanel panel = new JPanel();
GridBagLayout gbag = new GridBagLayout();
panel.setLayout(gbag);
GridBagConstraints c = new GridBagConstraints();
JButton btn1 = new JButton("One");
c.fill = GridBagConstraints.BOTH;
//c.fill = GridBagConstraints.HORIZONTAL;
c.anchor=GridBagConstraints.NORTHWEST;
c.gridx = 0;
c.gridy = 0;
c.weightx = 0.5;
c.weighty = 0.5;
panel.add(btn1, c);
JButton btn2 = new JButton("Two");
c.gridx++;
panel.add(btn2, c);
//c.fill = GridBagConstraints.BOTH;
JButton btn3 = new JButton("Three");
c.gridx = 0;
c.gridy++;
c.gridwidth = 2;
panel.add(btn3, c);
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String[] args) {
GBLFillBoth gBLFillBoth = new GBLFillBoth();
}
}
答案 3 :(得分:1)
您可以考虑使用MigLayout,代码更简单:
panel1Customizer();
panel2customizer();
panel3Customizer();
setLayout(new MigLayout("fill, wrap 3"));
add(panel1, "grow");
add(panel2, "grow");
add(panel3, "grow");