[英]Java How to thread a GUI
因此,我有一個打開while循環的按鈕,然后我的整個GUI凍結,直到while循環結束為止,也就是說我將如何使GUI每秒更新一次?
JButton Test= new JButton();
Test.setText("Test");
Test.setSize(230, 40);
Test.setVisible(true);
Test.setLocation(15, 290);
Test.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e){
int x = 0;
while(x<500){
x++
});
最主要的想法是您的GUI凍結,因為您在負責繪制GUI的線程中進行了大量處理。 解決方案是將可能占用時間的計算或任何處理委托給將在后台執行的線程。 https://docs.oracle.com/javase/tutorial/uiswing/concurrency/
這很明顯,因為Swing對象不是線程安全的,因此為您提供了SwingUtilities.invokeLater()
,它允許在以后的某個時間點執行任務。
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
int x = 0;
while(x<500){
x++
}
}
});
使用ExecutorService
類
Test.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ExecutorService es = Executors.newCachedThreadPool();
es.submit(new Runnable() {
@Override
public void run() {
int x = 0;
while (x < 500) {
x++;
}
}
});
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.