Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top