[英]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.