gpt4 book ai didi

java - 如何创建计时器任务的新实例而不是取消并重新启动它?

转载 作者:行者123 更新时间:2023-11-30 03:05:23 24 4
gpt4 key购买 nike

问题是我有一个项目,我必须在 java 上制作一个游戏。在我的游戏中,有一艘发射激光的宇宙飞船。我或多或少已经弄清楚了发射激光的机制,但我目前正在使用计时器任务来使激光飞过 JFrame 并给人留下激光被发射的印象。

问题是,一旦我开始多次拍摄,TimerTask 似乎就会出错。

主要目标是以给定速度在屏幕上移动对象

我还能做些什么来实现这一目标吗?有没有更好的方法来实现这个?我感谢我能得到的所有帮助,谢谢。这是一些代码:

public Space() {
this.setBackground(Color.BLACK);
this.setCursor(Cursor.getDefaultCursor());

this.addMouseMotionListener(new MouseAdapter() {
public void mouseMoved(MouseEvent e) {
repaint();
x = e.getX()-spaceFighterIcon.getIconHeight()/2;
y = e.getY()-spaceFighterIcon.getIconWidth()/2;

}
public void mouseDragged(MouseEvent e) {
repaint();
x = e.getX()-spaceFighterIcon.getIconHeight()/2; //Positions the cursor on the middle of the spaceShip and viceVersa
y = e.getY()-spaceFighterIcon.getIconWidth()/2;

}
}
);
this.addMouseListener(new MouseAdapter(){

public void mousePressed(MouseEvent e) {
if(timerRunning = true){
laserTimer.cancel();
laserTimer.purge();
laserFired = false;
}
if(SwingUtilities.isLeftMouseButton(e)){ // Gets where the laser is going to be shot from
repaint();
laserX = e.getX()-spaceFighterIcon.getIconWidth()/6;
laserY = e.getY();
laserFired = true;
}
if(SwingUtilities.isRightMouseButton(e)){

}
if(SwingUtilities.isMiddleMouseButton(e)){

}
}
});
}

public void paintComponent(Graphics g) {
this.graphics = g;
super.paintComponent(g);

spaceFighterIcon.paintIcon(this, g, x, y);
if(laserFired == true){
shootLaser();
}
}
public void shootLaser(){
laserIcon.paintIcon(this, graphics, laserX, laserY-50); // paints the laser
laserTimer = new Timer();
laserTimer.schedule(new AnimateLasers(), 0, 200); // Timer to move the laser across the frame
timerRunning = true;
repaint();
}
public void lasers(){
laserY = laserY-1; // function to move the laser
if(laserY <= 0){
laserTimer.cancel();
laserTimer.purge();
}
}
public class AnimateLasers extends TimerTask {

public void run() {
lasers();
repaint();
}
}

最佳答案

首先查看 Concurrency in SwingHow to use Swing Timers而不是java.util.Timer

Swing Timer 与 Swing 一起使用更安全,因为它在事件调度线程的上下文中执行它的计时

另请查看Painting in AWT and SwingPerforming Custom Painting有关绘画工作原理的更多详细信息

不要在绘制方法之外维护对 Graphics 上下文的引用。系统会告诉您的组件何时应该重新绘制它自己(通过调用 paintComponent 方法),本质上,您使用这段时间来更新“激光”的位置并调用 重新绘制,然后在被绘制系统调用时在paintComponent内绘制激光

关于java - 如何创建计时器任务的新实例而不是取消并重新启动它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34918747/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com