2014-10-05 134 views
0

我正在嘗試在java中創建類似於掃雷的JFrame應用程序,但規則和目標略有不同。點擊更改JButton ImageIcon

我創建了一個JButtons,12x12的網格並且有一個JButton 2D數組。

我試圖改變一個按鈕的圖像,當它被點擊(使它成爲X或金塊的圖像)。我知道如何做到這一點,如果我有每個按鈕的單獨名稱,但創建144個單獨的按鈕並命名每個按鈕似乎不合邏輯。因此,我需要做的是在該按鈕的單擊事件上,更改/設置該按鈕的圖像,但在我的動作偵聽器中,只有知道該按鈕的特定數組座標時,我才能算出它。

我的問題是如何更改該特定按鈕的圖像?或者我如何獲得按鈕[?] [?]的值,以便我可以更改該按鈕的圖像?

謝謝!

public class GoldPanel extends JPanel{ 

ImageIcon xImage = new ImageIcon("x.png"); 
ImageIcon goldImage = new ImageIcon(""); 

losingButtonListener loseButton = new losingButtonListener(); 
winningButtonListener winButton = new winningButtonListener(); 

JButton[][] button = new JButton[12][12]; 

//creates the layout 
GridLayout layout = new GridLayout(12,12); 

Random myRand = new Random(); 

public GoldPanel(){ 


    //creates panel for name/title/score/etc 
    JPanel titlePanel = new JPanel(); 
    add(titlePanel); 

    JLabel title = new JLabel("Welcome to the Goldmine Game!"); 
    titlePanel.add(title); 

    //creates panel for the game board 
    JPanel gamePanel = new JPanel(); 
    add(gamePanel); 
    gamePanel.setLayout(layout); 


    for(int i=0;i<12;i++) 
    { 
     for(int j=0;j<12;j++) 
     { 
      button[i][j] = new JButton(" "); 
      gamePanel.add(button[i][j]); 
      button[i][j].addActionListener(loseButton); 
     } 

    } 

    button[0][0].addActionListener(winButton); 

}//end constuctor 

private class losingButtonListener implements ActionListener { 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     // TODO Auto-generated method stub 



    }//actionPerformed 

}//buttonListener 

private class winningButtonListener implements ActionListener { 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     // TODO Auto-generated method stub 

     System.out.println("you win"); 



    }//actionPerformed 

}//winningButtonListener 


}//end GoldPanel class 

回答

2

如果你看看你ActionEvent Documentation Page看到,每一個動作事件構造有Object source。這意味着如果系統在按鈕上註冊點擊,該按鈕將被傳遞給ActionEvent的構造函數,如

所以你實際上通過將這個對象轉換爲正確的類來獲得正確的按鈕。

[...] 
public void actionPerformed(ActionEvent ae) { 
    JButton theRightButton = (JButton) ae.getSource(); 
    // do stuff with the button... 
} 
[...] 
+1

您也可以使用ActionEvent的actionCommand屬性,該屬性默認爲按鈕的文本,或者可以在按鈕本身上設置,作爲盲轉換或不得不使用'instanceof'的替代方法。 。你也可以使用一個'Action',允許OP傳遞一個被動作影響的對象的引用。 – MadProgrammer 2014-10-05 21:08:25

+0

這正是我所需要的。感謝您的幫助! – user2788749 2014-10-05 21:17:54

0

使用切換按鈕

http://docs.oracle.com/javase/7/docs/api/javax/swing/JToggleButton.html

所以擺動跟蹤狀態,爲您的按鈕模型。

擴展按鈕以通過X,Y座標在構造,並將它們存儲作爲場

附加相同的事件偵聽器,以所有的按鈕,投源按鈕類和檢索的被點擊的按鈕具有的x/y

動態更改的按下圖標到礦山或數在事件

呼叫點擊所有相鄰的空字段,如果你想複製這條規則,但要確保讓你不檢查按下狀態循環回已處理的鄰居。