我有這樣的代碼在這裏,例如用一個簡單的動畫,你按一下按鈕,並不斷通過使用線程中運行的JFrame。我做了UI與一個按鈕,實例JFrame的,問題是,當我再次單擊該按鈕,它的實例另一個JFrame的,第二個動畫不能正常工作。即使我實例化了5個JFrames,所有啓動動畫的按鈕也只能與第一個JFrame一起工作。我想要做的就是儘可能多的實例,並且它們都是分開工作的。這裏是動畫類的代碼:如何實例不是一個JFrame中使用線程Java中的動畫嗎?
public class duduleo extends JFrame implements ActionListener, Runnable{
JButton imagens;
int x=1;
static ImageIcon icon[] = new ImageIcon[11];
static JLabel l;
boolean anima=false;
public static void main(String args[]){
JFrame janela = new duduleo();
janela.show();
}
duduleo(){
icon[0]= new ImageIcon("duken1.jpg");
icon[1]= new ImageIcon("duken2.jpg");
icon[2]= new ImageIcon("duken3.jpg");
icon[3]= new ImageIcon("duken4.jpg");
icon[4]= new ImageIcon("duken5.jpg");
icon[5]= new ImageIcon("duken6.jpg");
icon[6]= new ImageIcon("duken7.jpg");
icon[7]= new ImageIcon("duken8.jpg");
icon[8]= new ImageIcon("duken9.jpg");
icon[9]= new ImageIcon("duken10.jpg");
icon[10]= new ImageIcon("duken11.jpg");
setSize(100,200);
setLocation(200,150);
getContentPane().setLayout(new GridLayout(2,1));
imagens = new JButton(icon[0]);
l= new JLabel(icon[0]);
imagens.addActionListener(this);
getContentPane().add(l);
getContentPane().add(imagens);
}
public void run(){
while(anima){
for(int i=0;i<icon.length;i++){
l.setIcon(icon[i]);
try{
Thread.sleep(100);
}catch(Exception e){}
}}}
public void actionPerformed(ActionEvent e){
anima=!anima;
Thread t;
t = new Thread(this);
t.start();
}}
感謝您的任何幫助。
不要在EDT上運行/ for循環。參見[Swing中的併發(http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html)和[事件分派線程(http://docs.oracle.com/javase/tutorial/ uiswing /併發/ dispatch.html) – asgs
沒有,沒有,當你點擊按鈕的第二次實例化另一個JFrame的。 –