我創建了2個JButtons.One中的一個具有按鈕功能,另一個處理圖像。如果此按鈕是clicked.So插入方法repaint()並添加一個監聽器到第一個JButton來改變圖像。當試圖添加監聽器或事件處理程序到第一個JButton時,沒有任何反應。所以圖像不會改變。任何人都可以顯示?我怎麼能我的方式,它的工作原理(改變按鈕被按下時,圖像)插入此監聽這裏是我的代碼:將事件處理程序添加到JButton中以重新繪製Java中的圖像時出現錯誤GUI
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.*;
import java.util.Random;
public class Back extends JFrame{
private Random ran;
private int value;
private JButton r;
private JButton c;
public Back(){
super("title");
ran = new Random();
value = nextValue();
setLayout(new FlowLayout());
r=new JButton("ROLL");
add(r);
Icon i=new ImageIcon(getClass().getResource("1.png"));
Icon img=new ImageIcon(getClass().getResource("2.png"));
c= new JButton(i);
if (value==1){
c= new JButton(i);
}
else if(value==2){
c= new JButton(img);
}
add(c);
thehandler hand=new thehandler(this);//konstruktori i handler merr nje instance te Background
r.addActionListener(hand);
c.addActionListener(hand);
}
private int nextValue() {
return Math.abs(ran.nextInt()) % 6 + 1 ;
}
public void roll() {
value = nextValue() ;
repaint() ;
}
public int getValue() {
return value ;
}
private class thehandler implements ActionListener{
private Back d;
thehandler(Back thisone) {
d = thisone ; }
public void actionPerformed(ActionEvent event) {
d.roll() ;
}
}
public static void main(String[] args) {
Back d = new Back() ;
d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
d.getContentPane().setBackground(Color.GREEN);
d.setSize(700,500);
d.setVisible(true);
}
}
沒有在你的代碼中你實際上改變了按鈕的狀態或它的初始創建後的圖像 – MadProgrammer
也許你應該看看[這個例子](http://stackoverflow.com/questions/28342538/java-swing - 時間和動畫 - 如何把它放在一起/ 28342986#28342986)一些更好的想法 – MadProgrammer