简体   繁体   English

Java Swing,ActionListener

[英]Java Swing, ActionListener

I'm writing simple minesweeper game. 我正在写简单的扫雷游戏。 I used 2 two-dimensional arrays, one is holding JButton and second array whether is bomb inside. 我使用了2个二维数组,其中一个是JButton,另一个是里面的炸弹。

JButton[][] tab = new JButton[8][8];
int[][] mine = new int[8][8];

In ActionLister I'm checking which button is actually clicked and if there is bomb inside. 在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 means there is bomb inside. 9表示里面有炸弹。

I wouldn't like to write 64 line of codes like this. 我不想写这样的64行代码。 How can I change this ? 我该如何更改?

Since I assume you are using Java 8 (or later), this should be the most simple solution: 由于我假设您使用的是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);
                }
            }
        });
    }
}

This way you won't have to save all the buttons, because you can access the button variable from inside the ActionListener. 这样,您不必保存所有按钮,因为您可以从ActionListener内部访问button变量。

When you are using Java 7 (or earlier), you farther have to declare the button variable as final 使用Java 7(或更早版本)时,您还必须将button变量声明为final

final JButton b = new JButton();

Alternatively you can also cast the source to JButton to get access to the source component from inside the action listener 或者,您也可以将源转换为JButton,以从动作侦听器内部访问源组件

public void actionPerformed(ActionEvent e){
    JButton b = (JButton)e.getSource();
    b.setText("B");
    b.setEnabled(false);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM