[英]Actions performed on jButton after disabling
我有使用Swing的示例代碼。
package playerlist;
import java.awt.FlowLayout;
import javax.swing.*;
import java.awt.event.*;
public class Sample extends JFrame{
private JButton button1;
private JButton button2;
public Sample(){
super();
setTitle("Sample JFrame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button1 = new JButton("Button 1");
button2 = new JButton("Button 2");
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
button1ActionPerformed(e);
}
});
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
button2ActionPerformed(e);
}
});
setLayout(new FlowLayout());
add(button1);
add(button2);
pack();
}
private void button1ActionPerformed(ActionEvent ae){
button1.setEnabled(false);
button2.setEnabled(false);
try{
Thread.sleep(5000);
}catch(Exception e){
}
System.out.println("*** Button 1 Clicked ***");
button1.setEnabled(true);
button2.setEnabled(true);
}
private void button2ActionPerformed(ActionEvent ae){
button1.setEnabled(false);
button2.setEnabled(false);
try{
Thread.sleep(5000);
}catch(Exception e){
}
// I have disabled this button from button 1's action, but still when I click this button within
// 5 seconds, actions of this button is performed
System.out.println("*** Button 2 Clicked ***");
button1.setEnabled(true);
button2.setEnabled(true);
}
public static void main(String [] args){
new Sample().setVisible(true);
}
}
我想 - 當我點擊button1(當button1的動作開始時),應該禁用button1和button2(如果我點擊禁用按鈕,則不應該執行任何動作)。 我已使用setEnabled(false)禁用了這兩個按鈕。 當button1的操作完成時,應啟用兩個按鈕。 但是在我的代碼中,這不起作用,即使在禁用按鈕后,也會對禁用按鈕執行操作。 在button1的操作中,我已禁用兩個按鈕並使用睡眠方法暫停執行(用於模擬繁重的工作)5秒,但在5秒內如果我單擊任何按鈕,則在完成button1的操作后觸發它們的操作。 請幫我。 我提供了示例代碼,當您運行它時,單擊button1后,然后立即按鈕2,執行兩個按鈕的操作。 我想按下任何按鈕時,按鈕的點擊操作將完成繁重的工作,同時我將禁用所有按鈕,因此不能執行任何其他操作。 第一個操作完成后,我將啟用所有按鈕。 請幫我。 提前致謝。
代碼邏輯可能是正確的,
但有一個錯誤,你通過Thread.sleep(int)
事件調度線程
必須將Thread.sleep(int)
更改為Swing Timer
然后第一步是JButton#setEnabled(false) ,其余代碼應該從Swing Timer調用的Swing Action中觸發
我通過在新線程上單擊按鈕執行任務來完成此工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.