[英]JButton stays pressed and I can't click and anything when I play a song on my GUI
[英]why i can't do anything in my application when Jbutton is pressed and performing its defined function in java?
這就是我試圖做到這一點的方式:
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Hello there");
Thread.sleep(1000);
panel.updateUI();
}
});
我將 Enter 按鈕設置為默認按鈕,所以當我繼續按下它時,按鈕可能按下 100 次或更多,但是因為我使用的是Thread.sleep(1000)
需要一些時間,所以我有時間輸入我的 JtextField 甚至關閉window 但無能為力。
另外,我嘗試將btnNewButton.addActionListener()
放在線程的 run 方法中,但沒有區別。
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Hello there");
Thread.sleep(1000);
panel.updateUI();
}
});
}
});
thread.start();
// I used try catch block in real code
誰能幫我解決這個問題?
**我正在使用 windowsBuilder 在 eclipse 中創建此應用程序。
不完全確定你的代碼應該做什么,但如果你想按下按鈕,然后 1000 毫秒后它會檢查你的字段,你應該這樣做:
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("before 1000ms");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("after 1000ms");
System.out.println("Reading the text field ...");
}
});
thread.start();
System.out.println("after the thread");
Output:
after the thread
before 1000ms
after 1000ms
Reading the text field ...
這是因為稱為 EDT 的東西 - 事件調度線程。
這個專用線程負責 GUI 中的所有事件——包括繪圖(刷新)和交互(按鈕單擊)。 這意味着,用於繪制應用程序的線程與用於執行actionPerformed
代碼的線程完全相同。 由於您實際上是在暫停該線程一段時間,因此您的應用程序將在該確切時間段內無響應。
由於不阻塞應用程序,在用戶交互上執行的任何內容都應該簡短且執行速度快。 如果您需要做一些繁重的工作,有一個稱為SwingWorker
的工具,它允許您輕松地在后台線程(池)中進行一些處理並在執行期間安排 UI 更新(如更新進度條)
在您的第二個“線程”片段中,您的線程除了將actionListener
添加到按鈕之外沒有做任何事情,然后它終止(可能在不到 1 毫秒后;)) - 動作回調仍然由 EDT 執行。 如果您從run
方法內部start
該自定義線程 - 那么它確實是並行的並且 GUI 不會被凍結 - 但同樣, SwingWorker
是通往 go 的方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.