如何编写一个事件,该事件在按下键(特别是空格键)时开始,在按住键时继续运行,并且仅在释放键时停止?我正在尝试模拟在粗糙表面上移动的带轮物体。我试过使用原始的 KeyListener 方法,但问题是,当我按住空格键时,我正在模拟的对象反复停止和启动。我听说一个可能的解决方案是键绑定,但即使在阅读了有关它的 Java 教程后我仍然不理解它们。
这是用于模拟的绘制方法(由每 10 毫秒休眠的线程控制):
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Shape roadsurface = new Rectangle2D.Float(0, 85, 1000, 200);
g2.setColor(Color.BLACK);
g2.setStroke(new BasicStroke(10));
g2.draw(roadsurface);
g2.setColor(new Color(102, 102, 153));
g2.fill(roadsurface);
Image carimage = Toolkit.getDefaultToolkit().getImage("cargrey.png");
g2.drawImage(carimage, x_pos, y_pos, 60, 30, this);
g2.finalize();
}
以下是用于更改 x_pos 的方法(假定未声明的变量已在类主体中声明):
public void accelerate()
{
do
{ acc = 15.0 - t;
vel = ( t * 15.0) - ( 0.5 * Math.pow(t, 2.0) );
disp = ( 0.5 * 15.0 * Math.pow(t, 2.0) ) - ( (1.0/6.0) * Math.pow(t, 3.0) );
x_pos = (int)disp;
t += 0.01; break;} while (acc > 0);
while (acc <= 0)
{ acc = 0;
disp = t * vel;
x_pos = (int)disp;
t += 0.01;
}
}
public void brake(double vel, double disp)
{
double u = 0;
double disp2;
while (vel > 0)
{
disp2 = (vel * u) + (0.5 * -100 * Math.pow(u, 2.0) );
vel = vel + (-100 * u);
x_pos = (int)(disp + disp2);
u += 0.01;
t += 0.01; break;}
while (vel <= 0)
{
u += 0.01;
t += 0.01;
}
}
这是我对这次活动的最初想法:
class Key1 extends Thread implements KeyListener
{
Track g;
boolean keyIsPressed;
Key1(Track g)
{
this.g = g;
}
public void keyTyped(KeyEvent ke) {}
public void keyPressed(KeyEvent ke)
{
if (ke.getKeyCode() == KeyEvent.VK_SPACE)
keyIsPressed = true;
}
public void keyReleased(KeyEvent ke)
{
if (ke.getKeyCode() == KeyEvent.VK_SPACE)
keyIsPressed = false;
}
public void run()
{
while (keyIsPressed)
{
g.repaint();
g.accelerate();
try
{
Thread.sleep(10);
}
catch (InterruptedException ex)
{
// swallowed
}
while (!keyIsPressed)
{
g.repaint();
g.brake(g.vel, g.disp);
try
{
Thread.sleep(10);
}
catch (InterruptedException ex)
{
// swallowed
}
}
}