Javax.swing 计时器重复良好,但 ActionListener 不执行任何操作 [英] Javax.swing timer repeats fine, but ActionListener doesn't do anything

查看:23
本文介绍了Javax.swing 计时器重复良好,但 ActionListener 不执行任何操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在文本字段中闪烁背景颜色.我的定时器设置如下:

I am trying to flash the background colour in a textfield. My timer setup is as follows:

 Flash flash = new Flash();                      //set up timer
 tmr = new javax.swing.Timer(1000, new Flash());
 tmr.addActionListener(flash);
 tmr.setInitialDelay(0);
 tmr.setRepeats(true);
 tmr.start();                 

我的actionListener如下:

My actionListener is as follows:

 static class Flash implements ActionListener
 {
    public void actionPerformed(ActionEvent evt)
    {
        if (flasher)
        {
            SpreademPanel.historyPnl.NameTxt.setBackground(Color.white);
        }
        else
        {
            SpreademPanel.historyPnl.NameTxt.setBackground(Color.pink);
        }
        flasher = !flasher;
    } //actionPerformed
} //Flash

现在,当我将其放入调试并执行操作时,该程序会重复执行 Flash 并在两个选项之间切换.但在屏幕上,只有第一个切换发生.之后没有任何动作,虽然闪光灯仍在运行.

Now, when I put this in debug and follow the action, the program does repeatedly step through flash and toggle between the two alternatives. But onscreen, only the first toggle occurs. After that, no action, although flash is still functioning.

这里出了什么问题?

在此先感谢您的帮助.

推荐答案

这里有几个问题.

第一个明显的事情是您似乎在使用可变静态.这是一个非常糟糕的主意,表明(并导致!)混乱.在这种特殊情况下,导致的问题之一是 flasher 静态是共享的.

The first obvious thing is that you appear to be using mutable statics. This is a really bad idea and indicates (and causes!) confusion. In this particular case, one of the problems caused is that the flasher static is shared.

Flash flash = new Flash();                      //set up timer
tmr = new javax.swing.Timer(1000, new Flash());
tmr.addActionListener(flash);

我们正在添加两个 Flash 操作.通常这会很糟糕,但只会产生一个无法检测的错误".颜色将设置两次.

We are adding two Flash actions. Ordinarily this would be bad, but just produce an undetectable "bug". The colour would be set twice.

把这两个东西放在一起,我们有两个不间断的动作来执行相同的切换.两个切换.状态不会改变(虽然有重绘、属性改变事件等).

Bring these two things together, and we have two actions without a break that perform the same toggle. Two toggles. The state does not change (although there are repaint, property change events, etc.).

所以,不要使用可变静态,并保持代码干净.

So, don't use mutable statics, and keep the code clean.

这篇关于Javax.swing 计时器重复良好,但 ActionListener 不执行任何操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆