gpt4 book ai didi

java - 使用 GridBagLayout (Java) 构建 GUI

转载 作者:行者123 更新时间:2023-12-01 11:42:31 25 4
gpt4 key购买 nike

我正在尝试使用 GridBagLayout 为一个小型 Java 游戏构建 GUI。最后它应该看起来像这样:

Box Drawing

这是我的代码:

    private GridBagConstraints c;

...

c.gridx = 1;
c.gridy = 0;
c.weightx = 0;
add(playButton, c);

c.gridx = 1;
c.gridy = 1;
c.weightx = 0;
add(optionsButton, c);

c.gridx = 1;
c.gridy = 2;
c.weightx = 0;
add(manualButton, c);

c.gridx = 1;
c.gridy = 3;
c.weightx = 0;
add(exitButton, c);

c.gridx = 0;
c.gridy = 4;
c.weightx = 1;
c.anchor = GridBagConstraints.SOUTHWEST;
add(creditsButton, c);

c.gridx = 2;
c.gridy = 4;
c.weightx = 1;
c.anchor = GridBagConstraints.SOUTHEAST;
add(legalNoticeButton, c);

目前看起来像这样:

Button Layout

我的问题是我可以将两个按钮设置到底部而不将其他四个底部设置到顶部?

最佳答案

@Gilbert Le Blanc 或多或少地解释了类似的事情(有细微差别):

基本上使用另一个面板将两个按钮向南移动并将它们分散到西和东:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestGridBagLayout {

protected void initUI() {
JFrame frame = new JFrame("test");
final JPanel centerPanel = new JPanel();
centerPanel.setLayout(new GridBagLayout());
JButton playButton = new JButton("Play");
JButton optionsButton = new JButton("Options");
JButton manualButton = new JButton("Manual");
JButton exitButton = new JButton("Exit");
JButton creditsButton = new JButton("Credits");
JButton legalNoticeButton = new JButton("Legal");
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
centerPanel.add(playButton, c);
centerPanel.add(optionsButton, c);
centerPanel.add(manualButton, c);
centerPanel.add(exitButton, c);

JPanel bottomPanel = new JPanel(new BorderLayout());
bottomPanel.add(creditsButton, BorderLayout.WEST);
// Filler component that avoids having the bottom panel too small
bottomPanel.add(new JComponent() {
@Override
public Dimension getPreferredSize() {
return new Dimension(centerPanel.getPreferredSize().width, 0);
}
});
bottomPanel.add(legalNoticeButton, BorderLayout.EAST);
frame.add(centerPanel);
frame.add(bottomPanel, BorderLayout.SOUTH);
frame.pack();
frame.setMinimumSize(frame.getPreferredSize());
frame.setVisible(true);
}

public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
UnsupportedLookAndFeelException {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.invokeLater(new Runnable() {

@Override
public void run() {
new TestGridBagLayout().initUI();
}
});
}
}

关于java - 使用 GridBagLayout (Java) 构建 GUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29417793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com