有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我为学校创建了一些程序,其中应该包含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;
        }
    }

类的构造函数:

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

}

我的错在哪里


共 (1) 个答案

  1. # 1 楼答案

    所以,在把你不完整的例子重新组合起来之后,我得到了

    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来展示你的问题。这不是一个代码转储,而是您正在做的一个示例,它突出了您所遇到的问题。这将减少混乱和更好的响应

    不要覆盖getXgetYJButton,而是将方法更改为类似getGridXgetGridY的方法