[英]Java JTextField cannot be updated
当我运行以下代码时,我在TextField
的级别上遇到问题。 在此过程中不会更新。 仅在完成所有计算后,它才会立即完全更新。
System.out.println("Start....!!");
MyJTextField.setText("Start....!!");
MyJTextField.setText("Result1 is calculated now….”);
/* here : Connect a DataBase and Make Calculations of the Var : Result1 */
System.out.println(Result1);
MyJTextField.setText("Result2 is calculated now….”);
/* here : Connect a DataBase and Make Calculations of the Var : Result2 */
System.out.println(Result2);
MyJTextField.setText("Result3 is calculated now….”);
/* here : Connect a DataBase and Make Calculations of the Var : Result3 */
System.out.println(Result3);
// and so ….
运行代码将执行以下操作:
之后,它将MyJTextField
完全更新MyJTextField
。
非常感谢您提供的有用帮助。
我将在匿名java.lang.Runnable
类中调用所有与Swing UI相关的方法,并将其传递给SwingUtilities.invokeLater(Runnable runnable)
来运行它。 这样可以确保在EDT(事件分派线程)上调用Runnable的run()
方法内部调用的UI操作。 切勿在例如执行更长时间的计算的同一线程上运行Swing操作。 参见下面的代码...
// non-ui thread
System.out.println("Start....!!");
// call on ui-thread (event dispatching thread)
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MyJTextField.setText("Start....!!");
MyJTextField.setText("Result1 is calculated now….”);
}
}
// non ui-thread again...
/* here : Connect a DataBase and Make Calculations of the Var : Result1 */
System.out.println(Result1);
// call on ui-thread again (event dispatching thread)
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MyJTextField.setText("Result2 is calculated now….”);
}
}
// and so ….
使用lambdas(Java8 +)的较短版本:
SwingUtilities.invokeLater(() -> MyJTextField.setText("Result2 is calculated now….”));
如果您使用的是Java swing库,则UI是由特定线程呈现的,这意味着线程会在从主线程进行计算的不同时间更新UI。
您应该尝试在Swing组件上使用validate()
或repaint()
方法来正确更新它们,如下所示:
MyJTextField.setText("Result1 is calculated now….”);
MyJTextField.validate();
// or MyJTextField.repaint();
它将立即完全更新。
所有代码都在Event Dispatch Thread (EDT)
,因此GUI仅在处理完成后才能重新绘制自身。
如果您的任务运行时间较长,则需要在单独的Thread
上执行该任务,以免阻塞EDT
,并且GUI能够重新绘制自身。
一种方法是使用SwingWorker
。 阅读Swing 并发教程中的这一节,以获取有关EDT以及如何使用SwingWorker
更多信息。
如果要在完成数据库访问时更新GUI,则可以“发布”更新。 这将确保在EDT上更新GUI。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.