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);
}
}
I'm attempting to create a metronome program, barebones, locked at 60BPM at the start. What I'm trying to figure out is when the timer goes through its task, the blue tile should move one space down. However, if a timer is implemented, the window is just blank. I was able to create a program for the first state of the metronome, here:
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);
}
}
}
}
But when I implement the timer into the paint function, it doesn't work as intended. How do I implement the timer into the paint function without giving me a window without anything in it?