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