java - 调度定时器
问题描述
我正在使用计时器来帮助模拟重力,并且当基于按键按下来安排计时器时,按键释放会给出一个错误,指出计时器已经安排或取消,我想知道如何解决它。我希望在用户释放空格键时安排一次计时器,并让它连续运行,直到它到达底部或按下空格键。帮助表示赞赏
import java.awt.event.*;
import javax.swing.*;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Calendar;
public class Game implements KeyListener {
JFrame frame;
JLabel player;
public boolean grounded = false;
public int velocity = 0;
public int finalY = 0;
public boolean spaceHeld;
public Timer flightTime;
public TimerTask flight;
public Timer gravityTime;
public TimerTask gravity;
Action spaceAction;
Game() {
frame = new JFrame("Nicholas Seow-Xi Crouse");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1920, 1080);
frame.setLayout(null);
frame.setFocusable(true);
frame.addKeyListener(this);
player = new JLabel();
player.setBackground(Color.red);
player.setBounds(10, 800, 50, 50);
player.setOpaque(true);
frame.add(player);
frame.setVisible(true);
flightTime = new Timer();
flight = new TimerTask() {
public void run() {
if(velocity > -5) {
velocity -= 1;
}
else{
velocity = -5;
}
if (finalY < -61) {
finalY = finalY + velocity;
}
else{
finalY = -61;
}
player.setLocation(player.getX(), player.getY() + finalY);
if (player.getY() <= 0){
cancel();
velocity = 0;
finalY = 0;
player.setLocation(player.getX(), 0);
}
}
};
gravityTime = new Timer();
gravity = new TimerTask() {
//creates a timer run method that simulates the falling gravity when not grounded
public void run() {
if(velocity < 5){
velocity += 1;
}
else{
velocity = 5;
}
//creates the variable the tells where the player is located
if (finalY < 61) {
finalY = finalY + velocity;
}
else{
finalY = 61;
}
player.setLocation(player.getX(), player.getY() + finalY);
if (player.getY() >= 1000){
cancel();
velocity = 0;
finalY = 0;
player.setLocation(player.getX(), 990);
}
}
};
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_SPACE){
if(spaceHeld == false) {
gravity.cancel();
flightTime.scheduleAtFixedRate(flight, 0 ,33);
spaceHeld = true;
}
else {
gravity.cancel();
}
}
//Cancel the other timer here so they don't overlap
gravity.cancel();
}
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_SPACE){
gravity.cancel();
spaceHeld = false;
flight.cancel();
gravityTime.scheduleAtFixedRate(gravity, 0, 33);
//Cancel the other timer here so they don't overlap
}
}
}
解决方案
推荐阅读
- jquery - 遍历文档中一个元素下的所有元素 > 然后 addClass
- sql - Oracle sql不同的id但相同的值
- azure - 不支持将托管磁盘添加到具有基于 blob 的磁盘的 VM
- .net - 将自定义 IHttpModule 添加到 web.config 会引发 500 错误
- typescript - 打字稿和重载函数的具体柯里化 - 如何?
- r - 使用 read_excel 函数导入 excel 文件:日期列未正确导入
- python - 如何在 Django Rest Framework 中将属性或对象注入到视图中?
- c++ - 相同的代码,相同的库版本,相同的编译器,不同的输出
- c# - 在 Visual Studio 中向 PL/SQL 添加参数
- java - 使用 List 和 String 类型的属性为 JSON 生成模型