I copied code from one of posts that in theory should work but it didn't.
Code I copied:
public class Keyboard {
private static final Map<Integer, Boolean> pressedKeys = new HashMap<>();
static {
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(event -> {
synchronized (Keyboard.class) {
if (event.getID() == KeyEvent.KEY_PRESSED) pressedKeys.put(event.getKeyCode(), true);
else if (event.getID() == KeyEvent.KEY_RELEASED) pressedKeys.put(event.getKeyCode(), false);
return false;
}
});
}
public static boolean isKeyPressed(int keyCode) { // Any key code from the KeyEvent class
return pressedKeys.getOrDefault(keyCode, false);
}
}
it gives two errors:
Cannot define static initializer in inner type jWindowComponent.Keyboard
The method isKeyPressed cannot be declared static; static methods can only be declared in a static or top level type
I tried every thing to fix it i could come up with but with no success. I wanted to make specialized UI for little project i am working. I need some way that i can change parameters of graph renderer mid render and needed something like this:
if (Keyboard.isKeyPressed(KeyEvent.VK_A)) {
x=0;
y=0;
}
When I press key it will zoom in or it will pump up resolution or move certain direction. I have an idea on how to do it but i have no idea how to make it respond to key presses. It is my first time doing any kind of input other than using terminal and i really want to do it outside of terminal. I tried everything i found and i am either blind or i have no idea how to make it work. I tried everything from this post but nothing worked.
Anyway it may be some weird shenanigans in other parts of my code here:
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JFrame;
public class jWindowComponent extends Canvas {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 1000; // Additional pixels needed for the frame
private static final int HEIGHT = 1000; // Additional pixels needed for the frame
@Override
public void paint(Graphics g) {
super.paint(g);
long percent = 0;
long percheck = 0;
for (int r = 0; r <= 2; r ) {
for (int y = 0; y < HEIGHT; y ) {
for (int x = 0; x < WIDTH; x ) {
if (Keyboard.isKeyPressed(KeyEvent.VK_A)) {
x=0;
y=0;
}
if (x==y) {
g.setColor(Color.BLACK);
} else {
g.setColor(Color.WHITE);
}
g.fillRect(x, y, 1, 1);
}
//percent = (long) (y * 100 / HEIGHT);
//if (percent == percheck) {
// // block of code to be executed if the condition is true
//} else {
// System.out.print(String.format("\033[