简体   繁体   English

如何使用 KeyListener 同时检测多个键?

[英]How to detect multiple keys at the same time using KeyListener?

The question says it all!问题说明了一切! Here is my code and my attempt at using nested if statements, which ultimately failed.这是我的代码和我尝试使用嵌套 if 语句的尝试,但最终失败了。 I just want to make my code so when the user is holding shift and down, it loads a different image:我只想编写我的代码,以便当用户按住 shift 并按下时,它会加载不同的图像:

package Michael;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class MyCanvas extends Canvas implements KeyListener /* Creates the     MyScreen method 
                                                        which extends (inherits) from 
                                                        Canvas and implements (uses) 
                                                        KeyListener. */
{
int myX = 100; // Set the initial x coordinate.
int myY = 100; // Set the initial y coordinate.

BufferedImage down; // Loads the Image.
{
    try
    {
        down = ImageIO.read(new File("Images/down.png")); /* Loads the image from 
                                                          'Images/down.png'.*/
    }

    catch (IOException e)
    {
        System.out.println("Cannot find image file."); /* If the file location is
                                                       non-existent, print on a new line
                                                       'Cannot find Image File'.*/
    }
} 

/* The exact same process is done for the next 9 images loaded, just with different,
appropriate, variable names and locations. */

BufferedImage downrun;
{
    try
    {
        downrun = ImageIO.read(new File("Images/downrun.png"));
    }

    catch (IOException e)
    {
        System.out.println("Cannot find image file.");
    }
}

BufferedImage left;
{
    try
    {
        left = ImageIO.read(new File("Images/left.png"));
    }

    catch (IOException e)
    {
        System.out.println("Cannot find image file.");
    }
}

BufferedImage right;
{
    try
    {
        right = ImageIO.read(new File("Images/right.png"));
    }

    catch (IOException e)
    {
        System.out.println("Cannot find image file.");
    }
}

BufferedImage runleft;
{
    try
    {
        runleft = ImageIO.read(new File("Images/runleft.png"));
    }

    catch (IOException e)
    {
        System.out.println("Cannot find image file.");
    }
}

BufferedImage runright;
{
    try
    {
        runright = ImageIO.read(new File("Images/runright.png"));
    }

    catch (IOException e)
    {
        System.out.println("Cannot find image file.");
    }
}

BufferedImage swoosh;
{
    try
    {
        swoosh = ImageIO.read(new File("Images/swoosh.png"));
    }

    catch (IOException e)
    {
        System.out.println("Cannot find image file.");
    }
}

BufferedImage swordraise;
{
    try
    {
        swordraise = ImageIO.read(new File("Images/swordraise.png"));
    }

    catch (IOException e)
    {
        System.out.println("Cannot find image file.");
    }
}

BufferedImage up;
{
    try
    {
        up = ImageIO.read(new File("Images/up.png"));
    }

    catch (IOException e)
    {
        System.out.println("Cannot find image file.");
    }
}

BufferedImage uprun;
{
    try
    {
        uprun = ImageIO.read(new File("Images/uprun.png"));
    }

    catch (IOException e)
    {
        System.out.println("Cannot find image file.");
    }
}

public MyCanvas() // The MyCanvas constructor.
{
    this.setSize(600, 400); // Makes the size of the canvas 600 x 400.
    this.addKeyListener(this); // Adds KeyListener.
    this.setBackground(Color.WHITE); // Make the background white.
    this.setFocusable(true); // Make the window automatically focused.
}

String image; // Creates the image variable as a string.

public void paint(Graphics g) // The paint method using Graphics.
{
    if (image == "down")
    {
        g.drawImage(down, myX, myY, 55, 55, null);
    }

    else if (image == "up")
    {
        g.drawImage(up, myX, myY, 55, 55, null);
    }

    else if (image == "left")
    {
        g.drawImage(left, myX, myY, 55, 55, null);
    }

    else if (image == "right")
    {
        g.drawImage(right, myX, myY, 55, 55, null);
    }

    else if (image == "swoosh")
    {
        g.drawImage(swoosh, myX, myY, 55, 55, null);
    }

    else if (image == "swordraise")
    {
        g.drawImage(swordraise, myX, myY, 55, 55, null);
    }

    else if (image == "downrun")
    {
        g.drawImage(downrun, myX, myY, 55, 55, null);
    }

    else
    {
        g.drawImage(right, myX, myY, 55, 55, null);
    }

}

@Override
public void keyPressed(KeyEvent e) // When the key is pressed:
{   
    if (e.getKeyCode() == KeyEvent.VK_DOWN) // If the down arrow is pressed:
    {
        image = "down";
        myY += 10; // Increase the y coordinate by 10 (moves down).
    }

    else if (e.getKeyCode() == KeyEvent.VK_UP) // If the up arrow is pressed:
    {
        image ="up";
        myY -= 10; // Decrease the y coordinate by 10 (moves up).
    }

    else if (e.getKeyCode() == KeyEvent.VK_LEFT) // If the left arrow is pressed:
    {
        image = "left";
        myX -= 10; // Decrease the x coordinate by 10 (moves left).
    }

    else if (e.getKeyCode() == KeyEvent.VK_RIGHT) // If the right arrow is pressed:
    {
        image = "right";
        myX += 10; // Increase the x coordinate by 10 (moves right)
    }

    else if (e.getKeyCode() == KeyEvent.VK_1) // If the 1 button is pressed:
    {
        image = "swordraise";
    }

    else if (e.getKeyCode() == KeyEvent.VK_SHIFT)
    {
        if (e.getKeyCode() == KeyEvent.VK_DOWN)
        {
            image = "downrun";
            myY += 50;
        }
    }

    repaint(); // Refresh the Images.
}

@Override
public void keyTyped(KeyEvent e) // When the key is typed:
{
    // TODO Auto-generated method stub
}

@Override
public void keyReleased(KeyEvent e) // When the key is released:
{
    if (e.getKeyCode() == KeyEvent.VK_1) // If the 1 button is released:
    {
        image = "swoosh";
    }

    repaint();
}
}

Much Appreciated!非常感激!

This answer offers a slightly different approach to Michael by storing all the key codes of pressed keys in an ArrayList data structure as opposed to a boolean array.这个答案通过将所有按下键的键代码存储在一个ArrayList数据结构而不是一个布尔数组中,为 Michael 提供了一种稍微不同的方法。

ArrayList<int> keys=new ArrayList();
//This ArrayList will hold all the key codes of currently pressed keys.

@Override
public void keyPressed(KeyEvent k){
    if(!keys.contains(k.getKeyCode())){
        keys.add(k.getKeyCode());
    }
}

@Override
public void keyReleased(KeyEvent k){
    if(keys.contains(k.getKeyCode())){
        keys.remove(keys.indexOf(k.getKeyCode()));
    }
}

To test if the shift key is currently pressed, run this code as the key code for shift is 16:要测试当前是否按下了 shift 键,请运行此代码,因为 shift 的键代码为 16:

    keys.contains(16);

You can create an array of booleans, representing whether one key is one or off right now .您可以创建一组布尔值,表示一个键是 one 还是 off right now

boolean[] keys = new boolean[500];//whatever the highest keycode is
//....
public void keyPressed(KeyEvent e){
    keys[e.getKeyCode] = true;
}

public void keyReleased(KeyEvent e){
    keys[e.getKeyCode] = false;
}

Then, in your update (or in this case, your paint ) method, you can use your array like this:然后,在您的更新(或在这种情况下,您的paint )方法中,您可以像这样使用您的数组:

public void update(){
    if (keys[KeyEvent.VK_SHIFT] && keys[KeyEvent.VK_DOWN]){
        //user is holding down both shift and down arrow key
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM