Java-KeyListener不起作用 [英] Java - KeyListener not working

查看:339
本文介绍了Java-KeyListener不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这一直让我想整天撕掉头发.我正在尝试这样做,因此当我按右箭头键时,速度将达到10.我知道使我的精灵移动的方法可以工作,因为如果事先设置一个值,它将在屏幕上移动.是KeyListener没做任何事情:

This has been making me want to tear out my hair all day. I'm trying to make it so when I press the right-arrow key, my speed will go to 10. I know that my methods that make my sprite move work, because if I set a value beforehand, it moves across the screen. It's the KeyListener that isn't doing anything:

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;

public class Sprite implements KeyListener{
    public Image player = Toolkit.getDefaultToolkit().getImage("player.png");
    int x, y, dx, dy;

    public void doInit(){
        JFrame window = new JFrame();
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setSize(600, 400);
        window.setLocationRelativeTo(null);
        window.getContentPane().add(new ImageDraw());
        window.setVisible(true);
        window.setIgnoreRepaint(true);
        window.createBufferStrategy(2);
        window.getContentPane().addKeyListener(this);
    }

    public Image getSpriteHandle(){
        return player;
    }

    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();
        if(keyCode == KeyEvent.VK_RIGHT){
                dx = 10;
         }
    }   //end keyPressed

    public void keyReleased(KeyEvent e) {
        int keyCode = e.getKeyCode();
        if(keyCode == KeyEvent.VK_RIGHT){
                dx = 0;
         }
    }

    public void keyTyped(KeyEvent arg0) {

    } 

    public int moveX(){
        return dx;
    }

}   //end class

请帮助我!

推荐答案

是KeyListener没做任何事情

It's the KeyListener that isn't doing anything

您不应该使用KeyListener.

You should NOT be using a KeyListener.

Swing旨在与键绑定一起使用.即使组件没有焦点,您也可以将Action映射到KeyStroke.

Swing was designed to be used with Key Bindings. You can map an Action to a KeyStroke even when a component doesn't have focus.

这篇关于Java-KeyListener不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆