Java 使用GridBagLayout格式化JPanel
因此,我正在为一个小游戏创建一个GUI,作为一个顶点。我有4个JPanel,我正试图使用GridBagLayout在一个框架上定位 目前看起来是这样的: 但我希望它在设计上更类似于此: 框架的代码:Java 使用GridBagLayout格式化JPanel,java,swing,Java,Swing,因此,我正在为一个小游戏创建一个GUI,作为一个顶点。我有4个JPanel,我正试图使用GridBagLayout在一个框架上定位 目前看起来是这样的: 但我希望它在设计上更类似于此: 框架的代码: public OverlordFrame() { buttonPanel = new ButtonPanel(); invPanel = new InventoryPanel(); statPanel = new PlayerStatsPanel(invPanel);
public OverlordFrame()
{
buttonPanel = new ButtonPanel();
invPanel = new InventoryPanel();
statPanel = new PlayerStatsPanel(invPanel);
monstPanel = new MonsterPanel();
this.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.ipadx = 10;
c.ipady = 50;
c.gridx = 0;
c.gridy = 0;
c.weightx = .1;
c.weighty = .4;
c.gridheight = 2;
c.fill = GridBagConstraints.VERTICAL;
c.anchor = GridBagConstraints.LINE_START;
this.add(invPanel, c);
c.gridx = 1;
c.gridy = 1;
c.weightx = .4;
c.weighty = .3;
c.gridwidth = 2;
c.gridheight = 0;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.CENTER;
this.add(buttonPanel, c);
c.gridx = 2;
c.gridy = 0;
c.weightx = .1;
c.weighty = .4;
c.gridwidth = 0;
c.anchor = GridBagConstraints.LINE_END;
this.add(statPanel, c);
c.gridx = 1;
c.weightx = .4;
c.weighty = .4;
c.anchor = GridBagConstraints.CENTER;
this.add(monstPanel, c);
this.setSize(1440, 810);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
注意:左边的空白区域是InventoryPanel,有点像在右边的位置,ButtonPanel,即6个按钮,应该像在坏的绘画图片中一样,按钮后面的白色区域(下面有4个按钮)应该放在monster所在的位置,右边的JLabel应该放在右上角。感谢您的帮助我不会仔细阅读您的代码,试图找出它不起作用的原因,我真的没有时间,但下面的示例似乎与您想要的非常接近
话虽如此,我可能会尝试使用一系列复合的
BorderLayout
s来产生相同的效果,但那只是我你的两张图片看起来并不一样,对我来说就像苹果和橘子。请澄清这就是问题所在,我正试图让它看起来更像绘画照片,但我无法将格式设置为work@LarryKruz如果您觉得这有帮助,请将答案视为已接受。
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridheight = 2;
gbc.weightx = 0.3;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
add(makePane(Color.BLUE), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.gridheight = 1;
gbc.weightx = 0.4;
gbc.weighty = 0.5;
add(makePane(Color.MAGENTA), gbc);
gbc.gridx = 2;
gbc.weightx = 0.1;
add(makePane(Color.YELLOW), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.gridwidth = 2;
gbc.weightx = 0.7;
gbc.weighty = 0.5;
gbc.fill = GridBagConstraints.BOTH;
add(makePane(Color.CYAN), gbc);
}
protected JPanel makePane(Color color) {
JPanel panel = new JPanel();
panel.setBackground(color);
return panel;
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}