我正在制作一个横跨jbuttons网格布局的游戏,只允许移动到相邻的网格jbuttons . 目标是尝试使其成为topleft(从btm右侧) . 我认为这就是相关的:
//这是我的方法,以确定它是否是一个有效的移动(我不希望你能够移动到任何地方,但相邻的点
public boolean goodMove(int x, int y) {
int val = Math.abs(current.x - x) + Math.abs(current.y - y);
return val == 1;
}
//这是actionlister中的逻辑,一个大的if else循环,现在只引用gridlayout中的jbuttons(游戏面板)
public void actionPerformed(ActionEvent e) {
JButton clicked = (JButton) e.getSource();
if (clicked == SHOWMINES) {
if (SHOWMINES.getText().equals("Show Mines")) {
showMines();
SHOWMINES.setText("Hide Mines");
} else {
hideMines();
}
} else {
if (clicked == NEWGAME) {
newGame();
} else {
if (clicked == SHOWPATH) {
if (SHOWPATH.getText().equals("Show Path")) {
showPath();
SHOWPATH.setText("Hide Path");
} else {
hidePath();
}
} else {
if (clicked == OKAY) {
resetGridSize(Integer.parseInt(gridSizeInput.getText()));
newGame();
} else {
}
int gs = Integer.parseInt(gridSizeInput.getText());
for (int i = 0; i < gs - 1; i++) {
for (int j = 0; j < gs - 1; j++) {
if (clicked == grid[i][j]) {
if (goodMove(i, j)) {//debug tester ,this is where the problem is.
System.out.println("TEST");
current = new Point(i, j);
grid[i][j].setBackground(Color.green);
grid[i][j].setText("=");
}else{System.out.println("TEST2");}
}
}
}
}
}
}
}// end of action listener
Grid [] []是我的网格按钮数组,gridSizeInput是可以调整gridsize的文本字段 .
在此先感谢(我是编程新手,所以如果可以,请保持简单:)
编辑:我忘了提及,它没有识别我的if(goodMove())循环,它只是打印出我的其他两个 .
编辑:我的问题是为什么不工作,没有按钮将被识别为在我的网格中被点击,我想我想要看看我写的东西是否明显错误 . 谢谢 .
编辑:好的,这是我的所有按钮的整个动作监听器 . 这是我的第一篇文章,对不起,我没有更多帮助 - 让我知道我还能添加什么 .
1 回答
你的问题可能就像你没有将你的for循环扩展得足够简单一样简单 . 尝试改变这个:
对此:
Edit
这是我为测试概念而创建的最小代码示例: