移动圆圈的滞后问题

时间:2014-01-15 19:08:54

标签: java swing jpanel paintcomponent keylistener

所以我正在为我的计算机科学课程制作一个游戏,几乎是制作游戏Frogger的修改版本,我首先开始在JPanel上移动一个圆圈来模仿青蛙的运动,我意识到这很烦人与按钮的交互之间滞后。有谁知道如何完全摆脱滞后或者可能减少它?任何提示或帮助将不胜感激!这是迄今为止仅针对圆圈运动的代码,如果您发现可以进行任何改进,请随时留下您的意见。

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();
    }
}
}

这是主文件:

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);
}
}

2 个答案:

答案 0 :(得分:1)

不要使用KeyListener。相反,你应该使用Key Bindings。

键盘延迟重复事件。使用Swing Timer来计划动画,而不是依赖于生成的关键事件。有关更多信息和示例,请参阅Motion Using the Keyboard

答案 1 :(得分:0)

尝试仅使用不带timer和actionlistener的keyListener。

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...