2

我的 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);
    }
4

1 回答 1

4

这是您的代码,格式有效。要使其工作,您需要执行以下操作:

  1. 所有按钮都需要相同数量的 weightx,以使它们之间的空间均匀分布
  2. 标题需要一些 weightx 来获取它的所有行
  3. 使用 fill=BOTH 使所有组件填充它们获得的空间
  4. 使用 gridwidth 使标题使用三列,而按钮仅使用一列
  5. 使用 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);
}
于 2013-07-24T15:53:22.147 回答