首頁  >  文章  >  Java  >  為什麼我的 Javax.swing 計時器有效重複,但 ActionListener 保持惰性?

為什麼我的 Javax.swing 計時器有效重複,但 ActionListener 保持惰性?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-28 11:00:02281瀏覽

Why does my Javax.swing Timer repeat effectively, but the ActionListener remains inert?

Javax.swing 定時器有效重複,但ActionListener 保持惰性

在為應用程式製作動畫時,發布者遇到了修改背景顏色的問題文字欄位正在透過計時器機制傳播,但預期的反應(重複的更改)並未在螢幕上顯示。相關程式碼片段對應於:

<code class="java">Flash flash = new Flash();
tmr = new javax.swing.Timer(1000, flash); 
tmr.addActionListener(flash); 
tmr.setInitialDelay(0); 
tmr.setRepeats(true); 
tmr.start();</code>

偵錯時,發現操作偵聽器循環遍歷其替代方案,但僅顯示初始變更。

解決方案

所呈現案例中的問題源自於 ActionListener 實作中的內部缺陷。為了修正這個問題並闡明底層操作,引入了一種替代解決方案,該解決方案對波動的飽和度等級進行建模:

<code class="java">public class FlashTest extends JPanel {
    // Building blocks
    Timer t = null; // Timer for the color transitions
    Queue<Color> clut = null; // Queue for holding a cycle of hues

    // Setup method
    FlashTest() {
        clut = new LinkedList<>(); // Initialize the color cycle
        for (int i = 0; i < N; i++) {
            clut.add(Color.getHSBColor(1, 1 - (i / N), 1));
        }
        for (int i = 0; i < N; i++) {
            clut.add(Color.getHSBColor(1, i / N, 1));
        }
        t = new Timer(50, new ActionListener() { // Timer for managing color transitions
            @Override
            public void actionPerformed(ActionEvent e) {
                setBackground(clut.peek()); 
                clut.add(clut.remove()); // Color transition management
            }
        });
        t.start(); // Commencement of color cycling
    }

    // Override necessitated by color cycling
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g); // Call to superclass method for component depiction
        g.drawString(s, getWidth() / 2 - w2, getHeight() / 2 + h2); // Draw the text
    }

    // Launcher
    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(new FlashTest());
            f.pack();
            f.setVisible(true);
        });
    }
}</code>

這裡,顏色循環維護在隊列中,從而能夠連續描述其進展。 “paintComponent”方法可確保目前顏色在背景中持續顯示。

這種補救措施不僅解決了原始問題,還展示了定時顏色過渡的實際實現。

以上是為什麼我的 Javax.swing 計時器有效重複,但 ActionListener 保持惰性?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn