gpt4 book ai didi

java - 如何在 ActionListener 进行时更新 swing UI

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:47:51 24 4
gpt4 key购买 nike

在我下面的代码中,我希望在应用程序加载数据时清除 TextArea。我还添加了一个 repaint() 但它仍然没有被清除。我是否必须以不同的方式通知它才能强制重绘?

    button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
textArea.setText("");
textArea.repaint();


String result = //call a REST API
textArea.setText(result);
}
});

最佳答案

我认为您想做的是在另一个线程中调用其余 api。您可以使用 SwingWorker 来完成它,它被设计为在另一个线程中运行大量任务而不会阻塞 gui。这是一个我非常喜欢的完整示例 Swing Worker Example

例子:

class Worker extends SwingWorker<Void, String> {

@Override
    protected Void doInBackground() throws Exception {
//here you make heavy task this is running in another thread not in EDT
// call REST API here

return null;
    }

   @Override
   protected void done() {
        //this is executed in the EDT
//here you update your textArea with the result
   }
}

doInBackground 方法完成后,执行 done 方法。然后 SwingWorker 通知任何 PropertyChangeListeners 关于状态属性更改为 StateValue.DONE。因此,您可以在此处覆盖此方法或使用 propertyChangeListener 实现来执行您想要的操作。

关于java - 如何在 ActionListener 进行时更新 swing UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19708646/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com