Reputation: 1
I'm making a basic program with Java. I got Input working with this code:
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];
}
I ran tests, I got a basic entity system working using an ArrayList, all was fine.
But then I ran into graphics.
I set up a Jcanvas class (extends Canvas) but upon adding it to my frame, the graphics will work just fine, but my input no longer works at all.
canvas = new Jcanvas();
canvas.setSize(width, height);
canvas.setBackground(Color.RED);
frame.add(canvas);
//input
frame.addKeyListener(new Input());
Is there a way to fix this, or will I be stuck with either graphics or input?
Here is my Jcanvas class for reference:
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){
}
}
Upvotes: 0
Views: 759
Reputation: 2998
Try adding:
//input
Input input = new Input();
frame.addKeyListener(input);
canvas.addKeyListener(input);
Upvotes: 2