java - JPanel GridLayout 使所有按钮位于同一位置

标签 java swing layout jpanel jbutton

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

所以我创建了面板,并创建了一个名为 Position 的类,它扩展了 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;
        }
    }

Position类的构造函数:

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

}

我的错误在哪里?

最佳答案

所以,在将你不完整的示例重新组合在一起后,我得到了......

Good output

然后我注意到 x/y您的 Position 中的属性按钮,这让我觉得你可能已经包含了 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;
    }


}

生成...

Bad ouptut

所以答案是,包含完整的 runnable example这说明了你的问题。这不是代码转储,而是您正在执行的操作的示例,它突出显示了您遇到的问题。这将减少困惑并获得更好的响应

并且不要覆盖 getXgetY JButton的,而是将方法更改为类似 getGridXgetGridY

关于java - JPanel GridLayout 使所有按钮位于同一位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35113647/

相关文章:

java - getHeight() 如何在 java 中工作,尤其是在 paintComponent 中

java - 全局更改整个框架JAVA的字体

android - 如何将两个 View 放在水平布局中,使一个向左对齐,另一个向右对齐?

Java Android : the button does not work after returning to the first layout

java - 非法参数异常 : No interpolator found for float during implementing Substance LAF

java字符串连接

java - JMenuItem 设置对齐方式和最大尺寸

python - 从布局中删除所有项目

java:Runnable和Thread接口(interface)的关系

java - Java应用程序在关闭时被终止而没有发送信号