簡體   English   中英

Java Swing,ActionListener

[英]Java Swing, ActionListener

我正在寫簡單的掃雷游戲。 我使用了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內部訪問button變量。

使用Java 7(或更早版本)時,您還必須將button變量聲明為final

final JButton b = new JButton();

或者,您也可以將源轉換為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