使用箭头键来控制图片 [英] Control Image with Arrow Keys

查看:271
本文介绍了使用箭头键来控制图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让我的形象根据什么方向我用键在屏幕上移动。现在,它并没有任何按键我preSS回应。出于测试目的,我只尝试实施使用右箭头键。我该如何获得图像时,关键是pressed应对?这是我到目前为止有:

 进口java.applet.Applet中;
进口java.awt.Graphics;
进口java.awt.event.ActionEvent中;
进口java.awt.event.ActionListener;
//进口java.awt.event.ActionEvent中;
//进口java.awt.event.ActionListener;
进口java.awt.event.KeyEvent中;
公共类EC扩展的Applet {
    / **
     *
     * /
    私有静态最后的serialVersionUID长1L =;
    INT X = 50;
    诠释Y = 50;
    INT DX,DY;
    公共无效键pressed(KeyEvent e而)
    {
        INT键code = e.getKey code();
        如果(键code == KeyEvent.VK_RIGHT)
        {
            DX = 1;
            X + = DX;
        }
    }
    公共无效调用keyReleased(KeyEvent e而)
    {
        INT键code = e.getKey code();
        如果(键code == KeyEvent.VK_RIGHT)
        {
            DX = 0;
        }
    }
    公共无效漆(图形G)
    {
        g.drawImage(IllustrationManager.player [0] [0],X,Y,NULL);
    }
}


解决方案

请参阅的运动使用以使用的KeyListener和一个更好的解决方案,它使用键绑定问题的键盘

I am trying to get my image to move across the screen based on what arrow keys I use. Right now it does not respond to any key I press. For testing purposes I have only tried implementing the use of the RIGHT arrow key. How would I get the image to respond when the key is pressed? This is what I have so far:

import java.applet.Applet; 
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//import java.awt.event.ActionEvent;
//import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;


public class EC extends Applet{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    int x=50;
    int y=50;
    int dx,dy;
    public void keyPressed(KeyEvent e)
    {
        int keyCode = e.getKeyCode();
        if(keyCode==KeyEvent.VK_RIGHT)
        {
            dx=1;
            x+=dx;
        }
    }
    public void keyReleased(KeyEvent e)
    {
        int keyCode = e.getKeyCode();
        if(keyCode==KeyEvent.VK_RIGHT)
        {
            dx=0;
        }
    }
    public void paint(Graphics g)
    {
        g.drawImage(IllustrationManager.player[0][0],x,y,null);
    }


}

解决方案

See Motion Using the Keyboard for the problems with using a KeyListener and a better solution which uses Key Bindings.

这篇关于使用箭头键来控制图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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