无法使用KeyListner移动我的图像

时间:2016-05-25 01:50:56

标签: java image swing keylistener

我正在制作一个口袋妖怪游戏,这个类只是将地图绘制到屏幕上并根据箭头键上检测到的击键移动角色,但keyPressed方法没有检测击键和我的角色不会动。我无法理解。

import java.awt.*;
import java.applet.*;
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.lang.Math.*;
import java.util.*;
import java.util.ArrayList;
import java.awt.Image.*;
import java.awt.event.KeyEvent;

public class map extends JApplet implements KeyListener
{
Image grass;
Image Sgrass;
Image sand;
Image CharDown, CharUp, CharLeft, CharRight;
Image finalboss;
Image drawn;
Image[][] gr = new Image[13][15];
public int X;
public int Y;
javax.swing.Timer t;
double ttt = 0;
double B = 0;
public void init()
{
    addKeyListener (this);
    grass = getImage(getCodeBase(),"Grass.jpg");
    Sgrass = getImage(getCodeBase(),"Non-Grass.jpg");
    sand = getImage(getCodeBase(),"Sand.jpg");
    finalboss = getImage(getCodeBase(), "PLeft.jpg");
    CharDown = getImage(getCodeBase(), "CharDown.gif");
    CharUp = getImage(getCodeBase(), "CharUp.gif");
    CharLeft = getImage(getCodeBase(), "CharLeft.gif");
    CharRight = getImage(getCodeBase(), "CharRight.gif");
    drawn = CharDown;
    grid();
}
public void grid()
{
    for(int i = 0; i<13; i++)
    {
        for(int j = 0; j<15; j++)
        {
            double x = Math.random();
            if(x<=0.70)
            {
                gr[i][j] = grass;
            }
            else if(x>0.70 && x<=0.90)
            {
                gr[i][j] = Sgrass;
            }
            else if (x>0.90)
            {
                gr[i][j] = sand;
            }
        }
    }
}  
public void paint(Graphics g)
{
    int a = 0;
    int b = 0;
    for(int z = 0; z<13; z++)
    {
        for(int w = 0; w<15; w++)
        {
            g.drawImage(gr[z][w],a,b,50,50,this);
            a+=50;            
            if (a > 750)
            break;
        }
        b+=50;
        a = 0;
        if (b > 650)
        break;
    }
    g.drawImage(drawn, X, Y, 50, 50, this);
    g.drawImage(finalboss, 700, 600, 50, 50, this);
}
public void keyPressed(KeyEvent e)
{
    JOptionPane.showMessageDialog(null, "Key was pressed");
    int key = e.getKeyCode();
    if (key == 37)
    {
        //left
        X=X-50;
        drawn = CharLeft;
    }
    else if (key == 39)
    {
        //right
        X=X+50;
        drawn = CharRight;
    }
    else if (key == 38)
    {
        //up
        Y=Y-50;
        drawn = CharUp;
    }
    else if (key == 40)
    {
        //down
        Y=Y+50;
        drawn = CharDown;
    }
    repaint();
}
public void keyTyped(KeyEvent e) { }
public void keyReleased(KeyEvent e) { }
}

1 个答案:

答案 0 :(得分:0)

最可能的问题是您的JApplet没有焦点,因此事件被传递到不同的组件。您可以尝试一些解决方法。首先,您可以尝试将行setFocusable(true);添加到init()的{​​{1}}方法中。这不是最强大的解决方案,但我过去已成功使用它。或者,您可以按照this question中的建议使用KeyBinding。