[英]Java drawOval after random time when user pressed Jbutton
因此,當用戶按下我的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();
}
}
問題是您的邏輯:
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.
}
您可以使用Thread類中的sleep函數使程序等待隨機時間。 像這樣:
try{
Thread.sleep(PopUpTime);
}
catch(Exception e)
{}
// and then compute new points and repaint
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.