【发布时间】:2016-05-08 21:46:48
【问题描述】:
我为我的学校创建了一些应该包含n*n 按钮的程序。
按钮应采用矩阵布局,具有 n 行和 n 列。
所以我创建了面板,并创建了一个名为 Position 的类,它扩展了 JButtons - 我想要添加到面板的按钮。
我在面板中添加了布局:
this.setLayout(new GridLayout(n,n));
然后我创建 n*n Positions 按钮并将它们添加到面板中。
问题是,所有按钮都添加到同一个位置(屏幕左上角)——即使我可以在它们应该在的位置单击它们! (见屏幕截图,其中 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);
}
}
我的错误在哪里?
【问题讨论】:
-
不要将您的代码发布为图像。它应该是文本。
-
我想显示程序结果,我也写成文本
-
这样可以正常添加一个普通的
JButton。你能显示Position类的构造函数的代码吗? -
是的,我添加了位置类的代码
-
您是否覆盖了
JButton的getX和getY方法以返回您的x/y 值?
标签: java swing layout jpanel jbutton