我正在使用Java制作基本程序。我得到输入使用此代码:
package main;
import java.awt.event.KeyEvent;
import java.awt.event.KeyAdapter;
public class Input extends KeyAdapter{
public void keyPressed(KeyEvent ke){
_press[ke.getKeyCode()] = true;
_pressed[ke.getKeyCode()] = true;
}
public void keyReleased(KeyEvent ke){
_press[ke.getKeyCode()] = false;
_released[ke.getKeyCode()] = true;
}
public void update(){
for (int i = 0; i < _press.length; i ++){
_pressed[i] = false;
_released[i] = false;
}
}
/**
* checks if a key is being pressed
* @param key an integer representing a key(Key class recommended)
* @return boolean
*/
public static boolean check(int key){
if (_press[key]) return true; else return false;
}
/**
* checks if a key was pressed
* @param key an integer representing a key(Key class recommended)
* @return boolean
*/
public static boolean pressed(int key){
if (_pressed[key]) return true; else return false;
}
/**
* checks if a key was released
* @param key an integer representing a key(Key class recommended)
* @return boolean
*/
public static boolean released(int key){
if (_released[key]) return true; else return false;
}
protected static boolean[] _press = new boolean[128];
protected static boolean[] _pressed = new boolean[128];
protected static boolean[] _released = new boolean[128];
}
我运行了测试,我得到了一个使用ArrayList工作的基本实体系统,一切都很好。
然后我遇到了图形。
我设置了一个Jcanvas类(扩展了Canvas),但是在将它添加到我的框架后,图形工作得很好,但我的输入完全不再有效。
canvas = new Jcanvas();
canvas.setSize(width, height);
canvas.setBackground(Color.RED);
frame.add(canvas);
//input
frame.addKeyListener(new Input());
有没有办法解决这个问题,还是我会陷入图形或输入?
这是我的Jcanvas类供参考:
package main;
import java.awt.Canvas;
import java.awt.Graphics;
public class Jcanvas extends Canvas{
static final long serialVersionUID = 42L;
public void paint(Graphics g){
}
public void drawrect(int x, int y, int width, int height){
Graphics g = getGraphics();
//g.setColor(Color.blue);
g.drawRect(x, y, width, height);
}
public void drawfill(Graphics g, int x, int y, int width, int height){
}
}
答案 0 :(得分:2)
尝试添加:
//input
Input input = new Input();
frame.addKeyListener(input);
canvas.addKeyListener(input);