首页  >  文章  >  Java  >  为什么我的 Swing Timer ActionListener 不更新文本字段的背景颜色?

为什么我的 Swing Timer ActionListener 不更新文本字段的背景颜色?

Barbara Streisand
Barbara Streisand原创
2024-10-28 00:21:01785浏览

Why Doesn't My Swing Timer ActionListener Update the Text Field's Background Color?

Javax.swing 定时器重复,但 ActionListener 不执行

简介

在尝试为文本字段创建闪烁的背景颜色时,用户遇到了一个特殊问题:计时器函数按预期执行,但 ActionListener 没有触发颜色更改。这种差异使背景颜色在初始切换后保持不变。

计时器设置

此场景中的计时器设置遵循设置 Swing 的行业标准指南具有合理延迟、重复启用和 ActionListener 的计时器。计时器启动实现 ActionListener 接口的 Flash 类来处理颜色变化。

ActionListener 实现

ActionListener 在嵌套静态类中定义,包含基于内部布尔变量闪烁器切换背景颜色的逻辑。虽然调试确认操作正在执行,但初始切换后颜色变化并未反映在屏幕上。

根本原因和解决方案

问题的关键问题在于 Swing 组件(包括文本字段)需要显式调用 repaint() 方法来更新其外观。如果没有此调用,通过 setBackground() 或其他影响外观的方法所做的任何更改将对用户不可见。

修订的实现

要纠正该问题, ActionListener 应在更改背景颜色后调用 repaint()。这是 ActionListener 的修订版本:

<code class="java">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);
        }
        **SpreademPanel.historyPnl.NameTxt.repaint();** // Trigger repaint
        flasher = !flasher;
    } //actionPerformed
} //Flash</code>

通过添加 repaint() 调用,文本字段现在将根据 ActionListener 的逻辑正确更新其外观。

以上是为什么我的 Swing Timer ActionListener 不更新文本字段的背景颜色?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn