简体   繁体   中英

Event Listener to change the button color when clicked

How to change the focus listener to only action performed, so when the button clicked, it will trigger the fade method?

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

When you ask a question people need to know the context of the question. It looks like you copied the code from an answer like: How to slowly change object color from one to another?

That code was designed to fade the background on focusGained and focusLost events.

So your requirement is to do this on a button click. So basically you need to add an ActionListener to the button to invoke the the logic found in the focusGained(...) event.

One way to do this might be:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM