java - 移动圆时的滞后问题

  显示原文与译文双语对照的内容

因这里,我为我的电脑科学课做了一个修改版本,我首先只是在with上移动一个圆。 谁知道如何完全消除延迟或者减少延迟? 任何提示或者帮助都很感激。 下面是只有圆的运动,如果你看到任何改进,请随意留下你的评论。


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

public class second extends JPanel implements ActionListener, KeyListener 
{
Timer t = new Timer (5, this);
double x = 0, y = 0, velx = 0, vely = 0;

public second()
{
 t.start();
 addKeyListener(this);
 setFocusable(true);
 setFocusTraversalKeysEnabled(false);
}

public void paintComponent (Graphics g)
{
 super.paintComponent(g);
 Graphics2D g2 = (Graphics2D) g;
 g2.fill(new Ellipse2D.Double(x, y, 10, 10));
}

public void actionPerformed (ActionEvent e)
{
 repaint();
 x += velx;
 y += vely;
}

public void up()
{
 vely = -5;
 velx = 0;
}

public void down()
{
 vely = 5;
 velx = 0;
}

public void left()
{
 velx = -5;
 vely = 0;
}

public void right()
{
 velx = 5;
 vely = 0;
}

public void upEnd()
{
 velx = 0;
 vely = 0;
}

public void downEnd()
{
 velx = 0;
 vely = 0;
}

public void leftEnd()
{
 velx = 0;
 vely = 0;
}

public void rightEnd()
{
 velx = 0;
 vely = 0;
}

public void keyPressed (KeyEvent e)
{
 int code = e.getKeyCode();
 if (code == KeyEvent.VK_UP)
 {
 up();
 }
 if (code == KeyEvent.VK_DOWN)
 {
 down();
 }
 if (code == KeyEvent.VK_RIGHT)
 {
 right();
 }
 if (code == KeyEvent.VK_LEFT)
 {
 left();
 }
}

public void keyTyped (KeyEvent e) {}

public void keyReleased (KeyEvent e) 
{
 int code = e.getKeyCode();
 if (code == KeyEvent.VK_UP)
 {
 upEnd();
 }
 if (code == KeyEvent.VK_DOWN)
 {
 downEnd();
 }
 if (code == KeyEvent.VK_RIGHT)
 {
 rightEnd();
 }
 if (code == KeyEvent.VK_LEFT)
 {
 leftEnd();
 }
}
}

这是主要的file:


import javax.swing.JFrame;

public class Macheads
{
public static void main (String[] args)
{
 JFrame f = new JFrame();
 second s = new second();
 f.add(s);
 f.setVisible(true);
 f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 f.setSize(800,600);
}
}

时间: 作者:

不要使用。相反,你应该使用键绑定。

键盘因重复事件而延迟。 使用Swing计时器来调度动画,而不是依赖于要生成的关键事件。 有关更多信息和示例,请参见使用键盘 运动。

作者:

尝试仅使用不带计时器和actionlistener的。


public void keyPressed (KeyEvent e)
{
 int code = e.getKeyCode();
 if (code == KeyEvent.VK_UP)
 {
 up();
 }
 if (code == KeyEvent.VK_DOWN)
 {
 down();
 }
 if (code == KeyEvent.VK_RIGHT)
 {
 right();
 }
 if (code == KeyEvent.VK_LEFT)
 {
 left();
 }
 x += velx;
 y += vely;
 repaint();//added and will repaint everytime key is pressed
}

//no need to place arguments in keyTyped and keyReleased because JPanel is repainted on keypressed...

作者:
...