2017-10-01 138 views
0

如何將焦點偵聽器更改爲僅執行的操作,因此當點擊該按鈕時,會觸發淡入淡出方法?Event Listener點擊時更改按鈕顏色

class FaderTimer implements FocusListener, ActionListener { 
    private ArrayList colors; 
    private JButton component; 
    private Timer timer; 
    private int alpha; 
    private int increment; 

    FaderTimer(ArrayList colors, JButton component, int interval) { 
     this.colors = colors; 
     this.component = component; 
     component.addFocusListener(this); 
     timer = new Timer(interval, this); 
    } 

    public void focusGained(FocusEvent e) { 
     alpha = 0; 
     increment = 1; 
     timer.start(); 
    } 

    public void focusLost(FocusEvent e) { 
     alpha = steps; 
     increment = -1; 
     timer.start(); 
    } 

    public void actionPerformed(ActionEvent e) { 
     alpha += increment; 

     component.setBackground((Color) colors.get(alpha)); 

     if (alpha == steps || alpha == 0) { 
      timer.stop(); 
     } 
    } 
} 
    } 
+1

你需要兩個'ActionListener's,一個按鈕和一個用於'Timer' – MadProgrammer

+1

你還必須考慮到原代碼是淡入和淡出,所以你需要決定應該採取什麼行動(你在淡出還是輸出) – MadProgrammer

+0

當我點擊按鈕時,我想消失,那是怎麼回事? @MadProgrammer –

回答

0

當你問一個問題,人們需要知道的問題的情況下。它看起來像你從一個答案複製代碼,如:How to slowly change object color from one to another?

該代碼被設計爲淡入focusGained和focusLost事件的背景。

因此,您的要求是在點擊按鈕時執行此操作。所以基本上你需要添加一個ActionListener到按鈕來調用在focusGained(...)事件中找到的邏輯。要做到這一點

一種方式是:

//component.addFocusListener(this); 
component.addActionListener(new ActionListener() 
{ 
    @Override 
    public void actionPerformed(ActionEvent e) 
    { 
     alpha = 0; 
     increment = 1; 
     timer.start(); 
    } 
}); 
+0

是@camickr,我從你提供的鏈接複製了代碼,我很抱歉沒有在我的問題中包括源代碼鏈接,但是謝謝你的回答,我會試試。 –

+0

如果我想要當文本字段不爲空時使其淡入,當文本字段爲空時淡出,怎麼做@camickr –