문제

After I press a button, actionPerformed is called. A start a new Thread like this:

public void actionPerformed(ActionEvent evt) {
    try {
        Runnable r = new Runnable() {
            public void run() {
                try {
                    mylabel.setText("new text");
                    mylabel.revalidate();
                    mylabel.repaint();
                } catch (Exception x) {
                    x.printStackTrace();
                }
            }
        };

        Thread thread = new Thread(r);
        thread.start();
        MyFunction();

    // ...

After that on myLabel the string, new text, does not appear, just after actionPerformed run.

도움이 되었습니까?

해결책

You should run GUI related code in Event Dispatch Thread (EDT). Do not create another thread.

public void actionPerformed(ActionEvent evt) {
    try {
        SwingUtilities.invokeLater(
            new Runnable() {
                ...

If actionPerformed is the listener callback, it already runs on EDT. Create another Runnable if the callback takes long to execute, or it will "slow down" the GUI.

If MyFunction() method is not related to GUI repaint or anything like that, run it on another thread, specially if it is resource intensive.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top