我正在嘗試在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
您也可以使用ActionEvent的actionCommand屬性,該屬性默認爲按鈕的文本,或者可以在按鈕本身上設置,作爲盲轉換或不得不使用'instanceof'的替代方法。 。你也可以使用一個'Action',允許OP傳遞一個被動作影響的對象的引用。 – MadProgrammer 2014-10-05 21:08:25
這正是我所需要的。感謝您的幫助! – user2788749 2014-10-05 21:17:54