我正在编写简单的扫雷游戏。我使用了2个二维数组,第一个是保存JButton的,第二个数组里面是否有炸弹。
JButton[][] tab = new JButton[8][8];
int[][] mine = new int[8][8];
在 ActionLister 中,我检查实际单击了哪个按钮以及内部是否有炸弹。
public void actionPerformed(ActionEvent e) {
if(e.getSource()==tab[0][0] && mine[0][0]==9) {
tab[0][0].setText("B");
tab[0][0].setEnabled(false);
}
if(e.getSource()==tab[0][1] && mine[0][1]==9) {
tab[0][1].setText("B");
tab[0][1].setEnabled(false);
}
if(e.getSource()==tab[0][2] && mine[0][2]==9) {
tab[0][2].setText("B");
tab[0][2].setEnabled(false);
}
9表示里面有炸弹。
我不想写这样的64行代码。我该如何改变这个?
最佳答案
由于我假设您使用的是 Java 8(或更高版本),因此这应该是最简单的解决方案:
//code to create buttons and to place them on the frame / panel
for(int y = 0; y < 8; y++){
for(int x = 0; x < 8; x++){
JButton b = new JButton();
//place the JButton on your frame / panel
//probably you are using a GridLayout
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(mine[y][x] == 9){
b.setText("B");
b.setEnabled(false);
}
}
});
}
}
这样您就不必保存所有按钮,因为您可以从 ActionListener 内部访问按钮变量。
当您使用Java 7(或更早版本)时,您还必须将按钮变量声明为final
final JButton b = new JButton();
或者,您也可以将源强制转换为 JButton,以从操作监听器内部访问源组件
public void actionPerformed(ActionEvent e){
JButton b = (JButton)e.getSource();
b.setText("B");
b.setEnabled(false);
}
关于Java Swing、 Action 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49964651/