首頁 > Java > java教程 > 主體

為什麼我的 Swing Timer ActionListener 不更新文字欄位的背景顏色?

Barbara Streisand
發布: 2024-10-28 00:21:01
原創
793 人瀏覽過

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() 或其他影響外觀的方法所做的任何更改將對使用者不可見。

修訂的實作
<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>
登入後複製

要修正問題, ActionListener 應在變更背景顏色後呼叫 repaint()。這是 ActionListener 的修訂版本:透過新增 repaint() 調用,文字欄位現在將根據 ActionListener 的邏輯正確更新其外觀。

以上是為什麼我的 Swing Timer ActionListener 不更新文字欄位的背景顏色?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!