addKeyListener() 不适用于 JPanel
2022-09-02 05:31:26
我正在尝试制作一个游戏引擎。我已创建游戏类,但错误存在于键盘类中。在这里,我留下一些代码。
所属分类:: 游戏
package transfer2pc.co.cc.game.tileengine;
import java.awt.Graphics;
import java.util.HashMap;
import javax.swing.JPanel;
import transfer2pc.co.cc.game.tileengine.input.KeyBoard;
public abstract class Game extends JPanel implements Runnable {
/**
*
*/
private static final long serialVersionUID = 640206679500196209L;
HashMap<String, ?> maps = null;
KeyBoard keyBoard = null;
public Game(){
super();
keyBoard = new KeyBoard(this);
setKeyBoard(keyBoard);
Thread th = new Thread(this);
th.start();
}
public void run(){
while(true){
repaint();
try {
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void paint(Graphics g){
}
public void addMap(){
}
public void setMap(){
}
public abstract void keyPressed(int code);
public abstract void keyReleased(int code);
public abstract void keyTyped(int code);
public void setKeyBoard(KeyBoard key){
addKeyListener(key);
}
}
所属分类:: 键盘
package transfer2pc.co.cc.game.tileengine.input;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import transfer2pc.co.cc.game.tileengine.Game;
public class KeyBoard extends KeyAdapter implements KeyListener {
Game game = null;
public KeyBoard(Game gm){
this.game = gm;
}
@Override
public void keyPressed(KeyEvent e) {
System.out.println("KeyPressed");
game.keyPressed(e.getKeyCode());
}
@Override
public void keyReleased(KeyEvent e) {
game.keyReleased(e.getKeyCode());
}
@Override
public void keyTyped(KeyEvent e) {
game.keyTyped(e.getKeyCode());
}
public static char getChar(int key){
return (char)key;
}
}
所属分类:: 按键测试
package transfer2pc.co.cc.game.tileengine.test;
import java.awt.Graphics;
import javax.swing.JFrame;
import transfer2pc.co.cc.game.tileengine.Game;
import transfer2pc.co.cc.game.tileengine.input.KeyBoard;
public class KeyTest extends Game {
/**
*
*/
private static final long serialVersionUID = 8557676950779023327L;
char pressed;
public KeyTest(){
super();
addKeyListener(new KeyBoard(this));
}
@Override
public void keyPressed(int code) {
pressed = KeyBoard.getChar(code);
}
@Override
public void keyReleased(int code) {
}
@Override
public void keyTyped(int code) {
}
@Override
public void paint(Graphics g){
g.drawString("You pressed: "+pressed, 20, 20);
}
public static void main(String[] args){
JFrame frame = new JFrame("KeyTest");
frame.setSize(640, 480);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.add(new KeyTest());
frame.setVisible(true);
}
}
但错误是没有抛出异常,并且输入未被读取。谁能说我这样做的正确方法。