我为我的学校创建了一些程序,其中应包含 n*n
按钮。
按钮应采用 n 行 n 列的矩阵布局。
所以我创建了面板,并创建了一个名为 Position
的类,它扩展了 JButton
s - 我想要添加到面板的按钮。
我向面板添加了布局:
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);
}
}
我的错误在哪里?
最佳答案
所以,在将你不完整的示例重新组合在一起后,我得到了......
然后我注意到 x
/y
您的 Position
中的属性按钮,这让我觉得你可能已经包含了 getX
和getY
方法,比如...
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这说明了你的问题。这不是代码转储,而是您正在执行的操作的示例,它突出显示了您遇到的问题。这将减少困惑并获得更好的响应
并且不要覆盖 getX
和getY
JButton
的,而是将方法更改为类似 getGridX
和getGridY
关于java - JPanel GridLayout 使所有按钮位于同一位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35113647/