0

我正在用Java制作一个基本程序。我让 Input 使用此代码:

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){
    }
}
4

1 回答 1

2

尝试添加:

//input
Input input = new Input();
frame.addKeyListener(input);
canvas.addKeyListener(input);
于 2012-08-02T23:40:16.843 回答