2

ここに、ボタンをクリックしてスレッドを使用して実行し続ける単純なアニメーションで JFrame をインスタンス化するこのコードがあります。JFrame をインスタンス化するボタンを使用して UI を作成しました。問題は、ボタンをもう一度クリックして別の JFrame をインスタンス化すると、2 番目の JFrame のアニメーションが正しく機能しないことです。たとえば 5 つの JFrame をインスタンス化したとしても、アニメーションを開始するすべてのボタンは最初の JFrame でのみ機能します。私がやりたいのは、私が望むだけインスタンス化することであり、それらはすべて個別に機能します。アニメーション付きのクラスのコードは次のとおりです。

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();
}}

助けてくれてありがとう。

4

1 に答える 1

2

Swing の invokeLater() を使用することになっていると思います。そうしないと、イベント ディスパッチ スレッドに置かれます。

イディオムを理解するために、ここの例を見てください: http://www.java2s.com/Code/Java/Swing-JFC/Swinginvokelater.htm

以下も参照してください。

invokeLaterの使用

Java デスクトップ アプリケーションの GUI 更新に EventQueue.invokeLater を使用する必要がありますか?

SwingUtilies.invokeAndWait/invokeLater をいつ使用するか

SwingWorker.doInBackground() 内で SwingUtilities.invokeLater() を使用する必要がありますか?

于 2012-10-15T14:20:53.263 に答える