gpt4 book ai didi

java - 使用 setText 在 jLabel 上设置文本被延迟

转载 作者:行者123 更新时间:2023-12-01 17:27:15 25 4
gpt4 key购买 nike

我正在使用 Netbeans IDE 使用 Java Swing 构建一个小型测试工具。

我正在尝试更新标签,但不知怎的,它没有被“重新绘制”/“刷新”。我研究了几个类似的问题,但无法解决我的问题。

private void excelFileChooserActionPerformed(java.awt.event.ActionEvent evt)
{
if(!JFileChooser.CANCEL_SELECTION.equals(evt.getActionCommand()))
{
String selectedFile = excelFileChooser.getSelectedFile().getAbsolutePath();
loaderLabel.setText("Please Wait..");
try {
//This is sort of a blocking call, i.e. DB calls will be made (in the same thread. It takes about 2-3 seconds)
processFile(selectedFile);
loaderLabel.setText("Done..");
missingTransactionsPanel.setVisible(true);
}
catch(Exception e) {
System.out.println(e.getMessage());
loaderLabel.setText("Failed..");
}
}
}

loaderLabel 是一个 JLabel,使用的布局是 AbsoluteLayout

所以,我的问题是“请稍等...”从未显示。尽管调用 processFile 方法大约需要 2-3 秒,但永远不会显示“请稍候...”。但是,会显示“完成...”/“失败...”

如果我在调用 processFile 之前添加一个 popup (JOptionPane),“请稍候..” 显示。我无法清楚地理解为什么会发生这种情况。

在进行大量方法调用之前,我是否应该遵循“良好实践”?我需要调用显式重绘/刷新/重新验证吗?

最佳答案

您需要调用

 processFile(selectedFile);

在另一个线程中(不在 AWT 线程中)。为此,您可以执行以下操作:

Thread t = new Thread(){
public void run(){
processFile(selectedFile);
// now you need to refresh the UI... it must be done in the UI thread
// to do so use "SwingUtilities.invokeLater"
SwingUtilities.invokeLater(new Runnable(){
public void run(){
loaderLabel.setText("Done..");
missingTransactionsPanel.setVisible(true);
}
}
)
}
};
t.start();

请注意,我很长时间没有使用 swing,因此此代码可能存在一些语法问题。

关于java - 使用 setText 在 jLabel 上设置文本被延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13971791/

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