简体   繁体   English

单击事件监听器以更改按钮的颜色

[英]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. 该代码旨在淡化focusGained和focusLost事件的背景。

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. 因此,基本上,您需要向按钮添加一个ActionListener,以调用focusGained(...)事件中找到的逻辑。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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