【问题标题】:Event Listener to change the button color when clicked单击时更改按钮颜色的事件侦听器
【发布时间】:2017-10-01 07:03:19
【问题描述】:

如何将焦点监听器改为只执行动作,这样当按钮点击时,会触发淡入淡出方法?

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

【问题讨论】:

  • 您需要两个ActionListeners,一个用于按钮,一个用于Timer
  • 您还必须考虑到原始代码正在淡入和淡出,因此您需要决定应该采取哪些操作(您是淡入还是淡出)
  • 我想在单击按钮时淡入,那是怎么回事? @MadProgrammer

标签: java swing button event-listener eventhandler


【解决方案1】:

当您提出问题时,人们需要了解问题的上下文。看起来您从以下答案中复制了代码: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();
    }   
});

【讨论】:

  • 是的@camickr,我从您提供的链接中复制了该代码,很抱歉没有在我的问题中包含源链接,但感谢您的回答,我会尝试一下。 .
  • 如果我想让它在文本字段不为空时淡入,并在文本字段为空时淡出,怎么做@camickr
猜你喜欢
  • 1970-01-01
  • 2021-07-07
  • 2012-12-06
  • 2016-09-08
  • 1970-01-01
  • 1970-01-01
  • 2021-05-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多