【问题标题】:Key Listener not working while using Image and Image Icon使用图像和图像图标时键侦听器不起作用
【发布时间】:2017-03-24 14:17:06
【问题描述】:

所以,我正在使用 ImageIcon 和 Image 为角色设置动画。到目前为止,我的代码使它看起来像角色正在运行,但是由于我无法弄清楚 KeyListener 不起作用的原因。我已经有一段时间了,我想知道我做错了什么。这是我的代码: *现在我采取上下移动,因为我不能左右工作。 velyY 将成为 y 的变化。

    import java.awt.BorderLayout;
    import java.awt.Graphics;
    import java.awt.MediaTracker;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.*;
    import java.awt.event.KeyEvent;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    import java.awt.Image;
    public class Main extends JPanel implements ActionListener,KeyListener{
    ImageIcon images[];
    int x = 100;
    int y = 5;
    int velX;
    int velY;
    int totalImages =3, currentImage = 0, animationDelay = 160;
    Timer animationTimer;
    public Main() {
    images = new ImageIcon[totalImages];
    images[0] = new ImageIcon("standing.png");
    images[1] = new ImageIcon("ready.png");
    images[2] = new ImageIcon("running.png");
    startAnimation();
    }

    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics g2 = (Graphics) g;
    if (images[currentImage].getImageLoadStatus() == MediaTracker.COMPLETE){
    Image img =  images[currentImage].getImage();
    g2.drawImage(img, x, 407, null);
    currentImage = (currentImage + 1) % totalImages;
     }
    }

    public void actionPerformed(ActionEvent e) {
    repaint();
    x+=velX;
    }

    public void right(){
    velX = 8;
    }
    public void left(){
    velX = -8;    
    }

    public void keyPressed(KeyEvent arg0) {
    int code = arg0.getKeyCode();
    if (code == KeyEvent.VK_A){
    left();
     }
    if(code == KeyEvent.VK_D){
    right();
     }
    }
    public void keyTyped(KeyEvent e){}
    public void keyReleased(KeyEvent e){
    velX = 0;
    velY = 0;
    }
    public void startAnimation() {
     if (animationTimer == null) {
      currentImage = 0;
     animationTimer = new Timer(animationDelay, this);
     animationTimer.start();
     } else if (!animationTimer.isRunning())
     animationTimer.restart();
     }

    public void stopAnimation() {
     animationTimer.stop();
      }  

     }//end class

【问题讨论】:

    标签: java image animation keylistener


    【解决方案1】:

    如果您希望面板管理关键事件,您必须将您的 KeyListener 注册到面板。

    第二件事是JPanel默认是不可聚焦的,所以你必须让它可聚焦才能接收关键事件。

    在您的 Main 构造函数中,只需添加:

    setFocusable(true); // make your panel focusable
    addKeyListener(this); // register the key listener
    

    【讨论】:

    • 谢谢,这解决了我的问题,但现在我有另一个问题。图片只重复一次然后停止更新。
    • 在添加关键监听部分之前动画是否正常工作?
    猜你喜欢
    • 2014-03-18
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多