我三歲就做了一個像寶石迷陣或糖果粉碎的遊戲。我創建了64個按鈕單位8x8。我想改變點擊按鈕的圖像。但我不能。如果你能幫忙,我會很高興。或者我該怎麼辦?點擊這個按鈕改變圖片
編輯:我很抱歉。我無法清楚地解釋我的問題。我的問題,我想改變點擊兩個按鈕的圖片。例如,我點擊按鈕[5],然後點擊按鈕[11]。然後按鈕[5]圖標應該是按鈕[11]圖標,[11]圖標應該是按鈕[5]圖標。
public class butondeneme extends JFrame{
private JPanel grid;
private JFrame jr;
public butondeneme(){
jr=new JFrame();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 640, 640);
grid=new JPanel();
grid.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
grid.setLayout(new GridLayout(8,8,5,5));
JButton[] buttons = new JButton[64];
//Creating random image for buttons
for (int i = 0; i<buttons.length; i++) {
Random r = new Random();
int a = r.nextInt(9)+1;
switch(a){
case 1 : buttons[i]=new JButton(new ImageIcon("img//Cakal.png"));
break;
case 2 : buttons[i]=new JButton(new ImageIcon("img//BugsBunny.png"));
break;
case 3 : buttons[i]=new JButton(new ImageIcon("img//Pig.png"));
break;
case 4 : buttons[i]=new JButton(new ImageIcon("img//Taz.png"));
break;
case 5 : buttons[i]=new JButton(new ImageIcon("img//Sam.png"));
break;
case 6 : buttons[i]=new JButton(new ImageIcon("img//DuffyDuck.png"));
break;
case 7 : buttons[i]=new JButton(new ImageIcon("img//Tweety.png"));
break;
case 8 : buttons[i]=new JButton(new ImageIcon("img//Slyvester.png"));
break;
case 9 : buttons[i]=new JButton(new ImageIcon("img//RoadRunner.png"));
break;
}
//Adding number to find easily
String comand=Integer.toString(i);
//Get ImageIcon name
final String imgName=((ImageIcon)buttons[i].getIcon()).toString();
buttons[i].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
}
});
buttons[i].setActionCommand(comand);
grid.add(buttons[i]);
}
add(grid);
}
public static void main(String[] args){
butondeneme erdem=new butondeneme();
erdem.setVisible(true);
}
}
只需使用'Button.setIcon(newImage)',會做:-) –