簡體   English   中英

在JFrame中使用Java計時器

[英]Using java timer in JFrame

當按下聽筒按鈕時,我希望綠色按鈕的顏色變為紅色。一定時間后,我還是要綠色按鈕。我不使用計時器類。請幫助我。

例如我的代碼

        if (e.getSource() == handsetbutton) {

                              text1.setBackground(Color.RED);

                          // What l have to add here?



        }

運行此示例。 我使用Swing計時器並將延遲設置為4秒。 當按下按鈕時,它會觸發一個更改顏色並啟動計時器的動作。 4秒后,顏色變回

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class GreenToRed extends JPanel {
    private Color color = Color.RED;                 // global color object
    static JButton button = new JButton("Change");
    private Timer timer = null;

    public GreenToRed(){

        timer = new Timer(4000, new ActionListener(){      // Timer 4 seconds
            public void actionPerformed(ActionEvent e) {
                color = Color.RED;                         // after 4 seconds change back to red
                repaint();
            }
        });


        button.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                color = Color.GREEN;        // change to green
                repaint();                  // repaint
                timer.start();              // start timer
            }
        });
    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame();
        frame.add(new GreenToRed(), BorderLayout.CENTER);
        frame.add(button, BorderLayout.SOUTH);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);

    }

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(color);
        g.fillOval(getWidth() / 2 - 50, getHeight() / 2 - 50, 100, 100);
    }

    public Dimension getPreferredSize() {
        return new Dimension(300, 300);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }
}

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM