JPanel GridLayout 使所有按钮都在同一个地方

JPanel GridLayout make all buttons be in same place

我为我的学校创建了一些应该包含 n*n 按钮的程序。 按钮应采用 n 行 n 列的矩阵布局。

所以我创建了面板,我创建了一个名为 Position 的 class,它扩展了 JButtons - 我想添加到面板的按钮。

我在面板中添加了布局:

this.setLayout(new GridLayout(n,n));

然后我创建了 n*n 个位置按钮并将它们添加到面板中。

问题是,所有按钮都添加到同一个位置(屏幕左上角)- 即使我可以在它们应该在的位置单击它们! (见屏幕截图,其中 n 为 4)

即使按钮不存在,我也可以点击灰色区域(空):

]1

面板构造函数:

    public GamePanel(int n) {
    super();
    this.n = n;
    positions = new Position[n][n];
    this.setLayout(new GridLayout(n,n));
    currX = new Random().nextInt(n);
    currY = new Random().nextInt(n);

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            Position p = new Position(i, j);
            this.add(p);
            positions[i][j] = p;
        }
    }

Positionclass的构造函数:

public class Position extends JButton {
private int x;
private int y;
private boolean visited = false;

public Position(int x, int y) {
    super("");
    this.x = x;
    this.y = y;
    this.setPreferredSize(new Dimension(50,50));
}

框架:

public class Game extends JFrame {
private GamePanel gamePanel;
public Game(int n){
    super();
    gamePanel = new GamePanel(n);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLayout(new BorderLayout());
    this.add(gamePanel,BorderLayout.CENTER);
    this.add(new JTextField(),BorderLayout.NORTH);
    this.pack();
    this.setVisible(true);
}

}

我的错误在哪里?

因此,在将您不完整的示例放回原处后,我得到...

然后我注意到你的 Position 按钮中的 x/y 属性,这让我觉得你可能包含了 getXgetY 方法,比如...

public class Position extends JButton {

    private int x;
    private int y;
    private boolean visited = false;

    public Position(int x, int y) {
        super("");
        this.x = x;
        this.y = y;
        this.setPreferredSize(new Dimension(50, 50));
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }


}

哪个生成...

所以答案是,包括一个完整的 runnable example 来证明您的问题。这不是代码转储,而是您正在做的事情的一个示例,它突出了您遇到的问题。这将导致更少的混乱和更好的响应

并且不要覆盖 JButtongetXgetY,而是将方法更改为 getGridXgetGridY