[英]Delay between two lines of code - Graphics
我正在尝试制作西蒙游戏 。 我在编写游戏程序时处于中途,但遇到了问题。 我希望程序从QUEUE中读取游戏中先前存在的所有值,并以正确的顺序闪烁其颜色(我选择将它们变为灰色,然后在第二秒后恢复正常),这就是我的问题。 如果您看一下play()
方法,您会看到我在那写的评论。 我怎么做?
这是我的代码:
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Arc2D;
import java.util.Date;
import javax.swing.JPanel;
import javax.swing.Timer;
import unit4.collectionsLib.Queue;
public class window extends JPanel implements MouseListener , ActionListener{
Queue <Integer>data = new Queue<Integer> ();
Queue <Integer>temp = new Queue<Integer> ();
int random;
Timer prestart;
int prestartcount;
Color [] colors = {Color.red,Color.blue,Color.yellow,Color.green};
public window (){
prestart = new Timer (1000,this);
int prestartcount=0;
prestart.start();
}
public void play (){
random = (int)(Math.random()*4);
data.insert(random);
int x=0;
Color temp=Color.black;
x = data.remove();
this.temp.insert(x);
temp = colors[x];
colors[x]=Color.gray;
// delay of one second here
colors[x]=temp;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(colors[0]);
g.fillArc(80, 150, 250, 250, 0, 360);
g.setColor(colors[1]);
g.fillArc(80, 150, 250, 250, 0, 270);
g.setColor(colors[2]);
g.fillArc(80, 150, 250, 250, 0, 180);
g.setColor(colors[3]);
g.fillArc(80, 150, 250, 250, 0, 90);
g.drawString(prestartcount+"", 0, 30);
repaint();
}
@Override
public void mouseClicked(MouseEvent arg0) {
arg0.getLocationOnScreen();
}
@Override
public void mouseEntered(MouseEvent arg0) {
}
@Override
public void mouseExited(MouseEvent arg0) {
}
@Override
public void mousePressed(MouseEvent arg0) {
}
@Override
public void mouseReleased(MouseEvent arg0) {
}
@Override
public void actionPerformed(ActionEvent act) {
if (act.getSource()==prestart){
if (prestartcount<3)
prestartcount++;
else{
prestart.stop();
play();
}
}
}
}
使用基于Swing的单拍Timer
翻转颜色并调用repaint()
。 有关详细信息,请参见在Swing应用程序中使用计时器 。
colors[x]=Color.gray;
// delay of one second here
timer = new Timer(0, new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
colors[x]=temp;
repaint(); //repaint the gui, or you want see the effect
}
});
timer.setInitialDelay(1000); //wait one second
timer.setRepeats(false); //only once
timer.start();
您可能必须将温度设置为最终温度,或将其存储在其他位置。
尝试使用Thread.sleep() 。
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. The thread does not lose ownership of any monitors.
您需要Thread.sleep(1000)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.