簡體   English   中英

禁用后在jButton上執行的操作

[英]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,執行兩個按鈕的操作。 我想按下任何按鈕時,按鈕的點擊操作將完成繁重的工作,同時我將禁用所有按鈕,因此不能執行任何其他操作。 第一個操作完成后,我將啟用所有按鈕。 請幫我。 提前致謝。

我通過在新線程上單擊按鈕執行任務來完成此工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM