簡體   English   中英

如何讓 JButton 在恢復到原來的顏色之前改變顏色一段時間

[英]How to get a JButton to change color for a period of time before reverting to its original color

晚上好,我想創建一個計算器,其按鍵在按下時會改變顏色,並在 3000 毫秒后返回其初始顏色(白色)。 為此,我實現了 JButton.setBackground() 方法並編寫了代碼使鍵在 3000 毫秒后恢復到原來的顏色。 但是,每次我單擊計算器鍵時,它都會等待 3000 毫秒,然后才將 JButton 值返回給我,它會更改顏色但不會恢復為原始顏色。 我嘗試了幾次演習,但沒有成功。 這是我的 JButton 代碼在返回其初始顏色之前更改給定顏色的代碼:

try {
    buttonOne.setBackground(Color.RED) ;
    Thread.sleep(millis:3000) ;
    buttonOne.setBackground(Color.WHITE);
} catch (InterruptedException interruptedException ) {
    InterruptedException.printStackTrace();
}

您不想在 UI 中使用 Thread.sleep(),因為您希望 UI 保持響應。

嘗試這樣的事情:

import javax.swing.Timer;

JButton buttonOne = new JButton("Click me");
Timer timer = new Timer(3000 ,afterButtonClicked);
timer.setRepeats(false);

ActionListener afterButtonClicked = new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        buttonOne.setBackground(Color.WHITE);
    }
};

在按鈕上的動作偵聽器中:

buttonOne.setBackground(Color.RED);
timer.start();

暫無
暫無

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

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