0
import java.awt.Color;
import java.awt.Graphics;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JFrame;

public class guiMethod extends JFrame
{

    public static void main(String[] args)
    {
        guiMethod metronome = new guiMethod();
        metronome.setTitle("Example GUI");
        metronome.setSize(400, 120);
        metronome.setBackground(Color.BLACK);
        metronome.setDefaultCloseOperation(EXIT_ON_CLOSE);
        metronome.setVisible(true);

    }

    public void paint(final Graphics g)
    {

        Timer metronome = new Timer();

        TimerTask task = new TimerTask()
        {
            public void run()
            {
                int numSquared = 0;

                if (numSquared > 3)
                {
                    numSquared = 0;
                }
                else
                {
                    numSquared++;
                }

                int col;
                int row;
                int x;
                int y;

                for (row = 0; row < 1; row++)
                {
                    for (col = 0; col < 4; col++)
                    {
                        x = col * 100;
                        y = (row * 100) + 20;

                        if (col == numSquared)
                        {
                            g.setColor(Color.BLUE);
                        }
                        else
                        {
                            g.setColor(Color.CYAN);
                        }
                        g.fillRect(x, y, 100, 100);
                    }
                }
            }
        };
        metronome.schedule(task, 0, 1000);
    }

}

我正在尝试创建一个节拍器程序,准系统,一开始就锁定在 60BPM。我想弄清楚的是,当计时器完成其任务时,蓝色瓷砖应该向下移动一个空间。但是,如果实现了计时器,则窗口只是空白。我能够为节拍器的第一个状态创建一个程序,在这里:

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JFrame;

public class guiMethod extends JFrame
{

    public static void main(String[] args)
    {
        guiMethod metronome = new guiMethod();
        metronome.setTitle("Example GUI");
        metronome.setSize(400, 120);
        metronome.setDefaultCloseOperation(EXIT_ON_CLOSE);
        metronome.setVisible(true);

    }

    public void paint(Graphics g)
    {
        int col; 
        int row;
        int x;
        int y;


        for (row = 0; row < 1; row++)
        {
            for (col = 0; col < 4; col++)
            {
                x = col * 100;
                y = (row * 100) + 20;

                if (col == 0)
                {
                    g.setColor(Color.BLUE);
                }
                else
                {
                    g.setColor(Color.CYAN);
                }
                g.fillRect(x, y, 100, 100);
            }
        }
    }


}

但是当我将计时器实现到绘图函数中时,它并没有按预期工作。如何在不给我一个没有任何东西的窗口的情况下将计时器实现到绘画功能中?

4

0 回答 0