因此,当用户按下我的JButton时,它会选择一个随机时间,之后,它会在屏幕上绘制一个椭圆形。但是,根据我现在的情况,它会在按下按钮后立即绘制椭圆。我想让它在随机时间后出现。
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();
}
}
答案 0 :(得分:0)
问题在于你的逻辑:
if event is start button, then setup oval and timer and call repaint();
假设重绘是在设定坐标处绘制椭圆。
您可能应该这样做:
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.
}
您的repaint()方法需要检查drawOval设置:
public void repaint() {
if (drawOval) {
// draw it
} else {
// may need to clear oval
}
// draw other stuff.
}
答案 1 :(得分:0)
您可以使用Thread类中的sleep函数使程序等待一段随机时间。像这样:
try{
Thread.sleep(PopUpTime);
}
catch(Exception e)
{}
// and then compute new points and repaint