使用GridBagLayout在JPanel中居中组件

时间:2013-07-24 14:19:18

标签: java swing jpanel layout-manager gridbaglayout

我的JPanel中具有GridBagLayout的组件对齐存在问题。 JLabel位于顶部,但未居中,下方的JButtons一直位于右侧。有什么方法可以将它们放在中心吗?这是我初始化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);
    }

1 个答案:

答案 0 :(得分:3)

这是您的代码,其形式有效。为了使其有效,您需要做以下事情:

  1. 所有按钮需要相同的重量x,以使空间均匀分布 他们之间
  2. 标题需要一些权重才能获得所有的行
  3. 使用fill = BOTH使所有组件填满他们获得的空间
  4. 使用gridwidth使标题使用三列,而按钮仅使用一列
  5. 使用JLabel的水平对齐方式使标题在其空间中居中

  6. 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);
    }