Java 中未使用 setText() 更新 JLabel 的值

Value of JLabel is not being updated using setText() in Java

我知道很多人以前问过这个问题,但我找不到任何解决我问题的答案。我的代码是这样的:

public void mouseClicked(MouseEvent arg0) {
    TEXT.setText("ON");
    myfunction(); //runs for a very long time
}

JLabel原文为"OFF"。现在,我想在单击鼠标时将文本更改为 "ON",但直到 myfunction() 完成后才设置文本(这可能需要几分钟)。

我试过无效功能,制作了一个单独的功能来设置文本,但没有任何效果。

请帮我解决这个问题!

问题是 mouseClicked(...)UI Thread. That is the Thread that is responsible for handling all sorts of user actions (like a mouse click) and also the drawing of components (like updating the text of the label on screen). If you execute your long running method call on the UI thread, it will be blocked and can't draw anything until execution is complete. You'll have to use multi threading 上执行以解决此问题。

以下可能不是最优雅的解决方案,但如果您不熟悉多线程,它将完成工作:

public void mouseClicked(MouseEvent arg0) {
    TEXT.setText("ON");
    (new Thread() {
        public void run() {
            myfunction();
        }
    }).start();
}

它将生成一个新的 Thread 来处理您的方法,这将使 UI Thread 继续执行其操作。考虑停用刚刚单击的按钮,这样用户就无法在执行过程中开始执行(这通常是您想要的..)