gpt4 book ai didi

java - 使用 GridBagLayout 在 JPanel 中居中组件

转载 作者:行者123 更新时间:2023-12-04 04:48:20 24 4
gpt4 key购买 nike

我的 JPanel 中有一个 GridBagLayout 组件的对齐问题。 JLabel 位于顶部,但不居中,下方的 JButton 一直位于右侧。有什么办法可以把它们都放在中间吗?这是我初始化 GUI 的方法。

public void initialize() {
JButton[] moveChoices = new JButton[3];
JPanel buttonsPanel = new JPanel();
buttonsPanel.setBackground(Color.green);
buttonsPanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JLabel welcome = new JLabel();
for(int i = 0; i < moveChoices.length; i++) {
moveChoices[i] = new JButton();
c.gridx = i;
c.gridy = 1;
if (i == 0) c.anchor = GridBagConstraints.EAST;
if (i == 2) c.anchor = GridBagConstraints.WEST;
moveChoices[i].addActionListener(this);
buttonsPanel.add(moveChoices[i], c);
}

moveChoices[0].setText("Rock");
moveChoices[1].setText("Paper");
moveChoices[2].setText("Scissors");

welcome.setText("Welcome to rock paper scissors! Please enter your move.");
c.gridy = 0; c.gridx = 1; c.insets = new Insets(10, 0, 0, 0);
buttonsPanel.add(welcome);
winText = new JLabel();
buttonsPanel.add(winText, c);
this.add(buttonsPanel);
}

最佳答案

这是您的代码,它以一种有效的形式出现。要使其工作,您需要做到以下几点:

  • 所有按钮都需要相同数量的 weightx,以使空间均匀分布
    他们之间
  • 标题需要一些 weightx 才能获得其所有行
  • 使用 fill=BOTH 使所有组件填充它们获得的空间
  • 使用 gridwidth 使标题使用三列,而按钮仅使用一列
  • 使用 JLabel 的水平对齐方式使标题在其空间内居中

  • public void initialize() {
    JButton[] moveChoices = new JButton[3];
    JPanel buttonsPanel = new JPanel();
    buttonsPanel.setBackground(Color.green);
    buttonsPanel.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    JLabel welcome = new JLabel();
    c.fill=GridBagConstraints.BOTH;
    c.anchor=GridBagConstraints.CENTER;
    welcome.setText("Welcome to rock paper scissors! Please enter your move.");
    welcome.setHorizontalAlignment(SwingConstants.CENTER);
    c.weightx=1;
    c.gridy = 0; c.gridx = 0; c.insets = new Insets(10, 0, 0, 0);
    c.gridwidth=moveChoices.length;
    c.gridheight=1;
    buttonsPanel.add(welcome,c);
    c.insets=new Insets(0,0,0,0);
    c.gridwidth=1;
    for(int i = 0; i < moveChoices.length; i++) {
    moveChoices[i] = new JButton();
    c.gridx = i;
    c.gridy = 1;
    c.weightx=0.5;
    c.weighty=1;
    moveChoices[i].addActionListener(this);
    buttonsPanel.add(moveChoices[i], c);
    }

    moveChoices[0].setText("Rock");
    moveChoices[1].setText("Paper");
    moveChoices[2].setText("Scissors");
    this.add(buttonsPanel);
    }

    关于java - 使用 GridBagLayout 在 JPanel 中居中组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17836692/

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