1

わかりました、これは私の問題です:

プロジェクトの1つにカスタムダウンロードヘルパーを作成しようとしています。実装で複数のダウンロード(同時に実行)を許可したかったので、ダウンロードごとにスレッドを開始する必要があると考えました。

ただし、問題は、プログラムのGUIも更新したいということです。そのためには、Swingはスレッドセーフではないため、invokeLater()メソッドを使用したいと思いました。

現在:各スレッド内でinvokeLater()メソッドを使用してプログレスバーを更新すると、スレッドは自分のGUIをどのように認識しますか?このアプローチについてどう思うか、そしてこの問題をどのように解決するかを教えてください。

これも考慮してください:

public class frame extends JFrame {
    public frame() {
        //the constructor sets up the JProgressBar and creates a thread object
    }

    public void getFiles() {
        // Here I would start the thread.
        thread.start();
    }
}

そして、これがスレッドを設定する別のクラスです。

public class theThread extends Thread {
    // Here I would create the thread with its constructor 

    public void run() {
        // Here comes some code for the file download process
        //
        // While the thread is running the method below gets called.
        updateGUI();
    }

    public void updateGUI() {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                // Here I need to place the code to update the GUI
                // However, this method has no idea of what the GUI looks like
                // since the GUI was setup in the class 'frame'.
            }
        });
    } 
}    
4

1 に答える 1

1

フレームをパラメーターとして受け取るコンストラクターを作成できます。

public class TheThread extends Thread {
    private final JFrame frame;

    public TheThread(Runnable r, JFrame frame) {
        super(r);
        this.frame = frame;
    }
}

frame.doSomething(); これで、メソッドから呼び出すことができますupdateGUI

Runnable一般に、を拡張するよりも実装する方が適切であることに注意してくださいThread

または、説明した内容(UIを更新するバックグラウンドスレッド)などの状況を処理するように設計されたSwingWorkersを使用することもできます。

于 2013-01-28T16:39:39.993 に答える