Java drawOval after random time when user pressed Jbutton
So when the user presses my JButton, it picks a开发者_高级运维 random time, and after that time, it will draw a oval to the screen. However, with what I have now, it draws the oval right after the button is pressed. I want it to appear after a random time.
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == startButton)
{
popUpTime = random.nextInt(5000);
timer = new Timer(popUpTime, this);
x = random.nextInt(400) + 70;
y = random.nextInt(400) + 100;
points[current++] = new Point(x, y);
timer.start();
start();
repaint();
}
}
You could use the sleep function from the Thread class to make the program wait for a random time. Something like this:
try{
Thread.sleep(PopUpTime);
}
catch(Exception e)
{}
// and then compute new points and repaint
The problem is your logic:
if event is start button, then setup oval and timer and call repaint();
assumedly repaint is drawing your oval at the set coordinates.
You probably should do something like this:
if (e.getSource() == startButton) {
drawOval = false; // flag to repaint method to NOT display oval
// setup timer
repaint(); // oval will not be drawn
else {
// assuming timer has fired (which is a bit weak)
x = ....;
y = ...;
drawOval = true;
repaint(); // oval will be drawn.
}
Your repaint() method will need to check the drawOval setting:
public void repaint() {
if (drawOval) {
// draw it
} else {
// may need to clear oval
}
// draw other stuff.
}
精彩评论