Java GridBagConstraints gridx和gridy无法正常工作?

时间:2011-12-06 14:19:57

标签: java swing awt jframe jpanel

我正在尝试使用gridxgridy约束来定位我的按钮。但他们不工作!如果我更改gridxgridy变量,则不会发生任何变化。如果我将填充更改为GridBagConstraintsNONE,则仍然无效。

我在这里错过了什么吗?

import java.awt.*;
import javax.swing.*;

public class Window extends JFrame{
    private static final long serialVersionUID = 1L;

    JFrame frame = new JFrame("GUI");
    JTextField username = new JTextField(20);

    public void CreateWindow(){
        JPanel pane = new JPanel();
        pane.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();

        c.fill = GridBagConstraints.NONE;

        JButton button = new JButton("Button 1");
        c.weightx = 1.0;
        c.weighty = 1.0;
        c.gridx = 3;   //Has no effect
        c.gridy = 5;   //Has no effect
        c.anchor = GridBagConstraints.NORTHWEST;//If I remove this, it still does not work.
        pane.add(button, c);                    
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.setSize(400, 600);
        frame.setResizable(true);           
        frame.setLocationRelativeTo(null);          
        frame.add(pane);
        frame.setVisible(true);    
    }
}

如果这很难理解,问题出在哪里:

JPanel pane = new JPanel();
            pane.setLayout(new GridBagLayout());
            GridBagConstraints c = new GridBagConstraints();

            c.fill = GridBagConstraints.NONE;

            JButton button = new JButton("Button 1");
            c.weightx = 1.0;
            c.weighty = 1.0;
            c.gridx = 3;   //Has no effect
            c.gridy = 5;   //Has no effect
            c.anchor = GridBagConstraints.NORTHWEST;    //If I remove this, it still does not work.
            pane.add(button, c);

1 个答案:

答案 0 :(得分:3)

自从我完成了swing布局以来已经有一段时间了,但是如果你的JPanel中有多个JComponent,那么gridX和gridY是否只有效果?看起来你只有一个JButton,所以GridBagLayout没有任何布局可以做。