单击时更改按钮颜色的事件侦听器

Event Listener to change the button color when clicked

如何将焦点侦听器更改为仅执行的操作,以便在单击按钮时触发淡入淡出方法?

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();
        }
    }
}
    }

当您提出问题时,人们需要知道问题的背景。您似乎从以下答案中复制了代码:

该代码旨在淡化 focusGained 和 focusLost 事件的背景。

因此您的要求是在单击按钮时执行此操作。所以基本上您需要向按钮添加一个 ActionListener 以调用在 focusGained(...) 事件中找到的逻辑。

一种方法可能是:

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