[英]Change JButton ImageIcon on Click
我試圖在Java中創建一個與Minesweeper相似但規則/目標稍有不同的JFrame應用程序。
我創建了一個12x12的JButtons網格,並具有JButton 2D數組。
我試圖更改單擊按鈕時的圖像(使其成為X或金塊的圖像)。 如果每個按鈕都有一個單獨的名稱,我知道該怎么做,但是創建144個單獨的按鈕並命名每個按鈕似乎不合邏輯。
因此,我需要做的是在該按鈕的click事件上,更改/設置該按鈕的圖像,但是在我的動作偵聽器中,如果我知道該按鈕的特定數組坐標,就只能弄清楚它。
我的問題是如何更改特定按鈕的圖像? 或者如何獲取按鈕[?] [?]的值,以便可以更改該按鈕的圖像?
謝謝!
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文檔頁面,則會看到每個動作事件都是使用Object source
構造的。 這意味着,如果系統注冊了對按鈕的單擊,則此按鈕將作為源傳遞給ActionEvent
的構造函數。
因此,實際上,您可以通過將該對象強制轉換為正確的類來獲得正確的按鈕。
[...]
public void actionPerformed(ActionEvent ae) {
JButton theRightButton = (JButton) ae.getSource();
// do stuff with the button...
}
[...]
使用切換按鈕
http://docs.oracle.com/javase/7/docs/api/javax/swing/JToggleButton.html
因此,swing在按鈕模型中為您跟蹤狀態。
擴展按鈕以在構造函數中傳遞x,y坐標並將其存儲為字段
將相同的事件偵聽器附加到所有按鈕,將源強制轉換為按鈕類,並檢索已單擊的按鈕的x / y
快速更改按下的圖標以挖掘事件中的數字或編號
如果要復制此規則,請單擊click到所有相鄰的空字段,但是請確保檢查按下狀態,以免回退已處理的鄰居。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.