import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.KeyEvent; import java.awt.image.BufferStrategy; import javax.swing.JFrame; public class Main extends Canvas implements Runnable { private static final long serialVersionUID = 1L; public boolean running = false; public int width; public int height; public Thread thread; inputHandler input; public Main(int width, int height) { this.width = width; this.height = height; Dimension size = new Dimension(width, height); setPreferredSize(size); setMinimumSize(size); setMaximumSize(size); input = new inputHandler(); addKeyListener(input); } private void init() { } public synchronized void start() { thread = new Thread(this, "main thread"); running = true; thread.start(); } public void run() { while (running) { render(); update(); } } public void render() { BufferStrategy bs = this.getBufferStrategy(); if (bs == null) { createBufferStrategy(2); return; } Graphics g = bs.getDrawGraphics(); g.setColor(Color.black); g.fillRect(0, 0, getWidth(), getHeight()); g.dispose(); bs.show(); } public void update() { System.out.println(input.keys[KeyEvent.VK_UP]); } public static void main(String[] args) { Main main = new Main(640, 480); JFrame window = new JFrame(); window.add(main); window.pack(); window.setVisible(true); window.setResizable(false); window.setTitle("buffer Strategy test"); window.setLocationRelativeTo(null); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); main.start(); } }
import java.awt.event.KeyEvent; import java.awt.event.KeyListener; public class inputHandler implements KeyListener { public boolean keys[] = new boolean[65536]; public void keyPressed(KeyEvent e) { int keycode = e.getKeyCode(); keys[keycode] = true; } public void keyReleased(KeyEvent e) { int keycode = e.getKeyCode(); keys[keycode] = false; } public void keyTyped(KeyEvent e) { } }
please note this is not my code i am following a youtube tutorial. so basicaly im trying to use booleans to save the key strokes as true using the key event method getKeyCode() rather than using many if statements to what key has been pressed. when i put a system println in my update method telling it to print the boolean value of the key up it is constantly false even if i press it. thanks