簡體   English   中英

如何在一段時間內禁用JButton?

[英]How to disable a JButton for certain period of time?

我想禁用JButton約10秒鍾。 有辦法嗎?

謝謝

使用Swing Timer ,當觸發時,它將在事件調度線程的上下文中通知已注冊的偵聽器,從而可以安全地從中更新UI。

有關更多詳細信息,請參見如何 在Swing中 使用Swing計時器並發。

首先閱讀@MadProgrammer的答案,並通過那里提供的鏈接。 如果您仍然需要基於這些建議的可行示例,請參考以下示例。

為什么解決方案比提出的幾種解決方案更好

這是因為它使用javax.swing.Timer來啟用按鈕,該按鈕使GUI相關任務可以在事件調度線程(EDT)上自動執行。 這樣可以避免將swing應用程序與非EDT操作混合使用。

請嘗試以下示例:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class SwingDemo extends JPanel {
    private final JButton button;
    private final Timer stopwatch;
    private final int SEC = 10;

    public SwingDemo() {
        button = new JButton("Click me to disable for " + SEC + " secs");
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JButton toDisable = (JButton) e.getSource();
                toDisable.setEnabled(false);
                stopwatch.start();
            }
        });
        add(button);
        stopwatch = new Timer(SEC * 1000, new MyTimerListener(button));
        stopwatch.setRepeats(false);
    }

    static class MyTimerListener implements ActionListener {
        JComponent target;

        public MyTimerListener(JComponent target) {
            this.target = target;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            target.setEnabled(true);
        }

    }

    public static void main(String[] args) {
        final JFrame myApp = new JFrame();
        myApp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myApp.setContentPane(new SwingDemo());
        myApp.pack();
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                myApp.setVisible(true);
            }
        });
    }
}

您可以使用ThreadTask或更簡單的Timer類。

您可以使用Thread.sleep(時間以毫秒為單位)

例如:Thread.sleep(10000); //睡眠10秒

JButton button = new JButton("Test");

    try {
        button.setEnabled(false);
        Thread.sleep(10000);
        button.setEnabled(true);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

但它必須在單獨的線程中,否則會使所有GUI掛起10秒鍾。

您可以發布有關代碼的更多詳細信息,我可以提供幫助

暫無
暫無

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

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