-3

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[%dA", 1));
                //    System.out.print("\033[2K");
                //    System.out.print(percent);
                //    System.out.println("%");
                //}
//
                //percheck = percent;
            }

        }

    }


    public static void main(String[] args) {
        JFrame frame = new JFrame("ColouringPixels - Lesson 9");
        frame.setSize(WIDTH, HEIGHT);
        frame.setResizable(false);
        frame.add(new jWindowComponent());
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }


    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);
        }
    }
    
} 

I use this code to learn new stuff (like i learned how to use jframe to render window and some more stuff that is existent no more in this code). I am relatively new to java so 90% of time i have no idea what am i doing (as you can see). It may be that solution is somewhere on internet but I failed to find it.

I will be thankful for anything that will solve this problem.

dragon1f
  • 1
  • 1
  • As already answered, creating a class which `implements KeyListener` is the way to go. It's not typical to get user input in the `paint` method. One way this problem can be solved is using a _Model-View-Controller_ architecture (MVC). Try looking for a Java Swing MVC tutorial. Hopefully that will help. :-) – cba Sep 15 '22 at 15:33

2 Answers2

0

Define your Keyboard class with static modifier or move it to another file. Also I assume that you are using Java 8 or so, where static declarations in inner classes not supported.

  • that is correct i tried that... but it didn't reset x and y coordinates... so there's that idea out of window... – dragon1f Sep 15 '22 at 17:42
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 20 '22 at 13:58
0

You could use a KeyListener to detect key presses.

Here's a simple implementation:

import java.awt.Canvas;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;

public class JWindowComponent extends Canvas implements KeyListener {

  public JWindowComponent() {
    // Since this class implements KeyListener, you can just add the KeyListener methods in
    // this class
    // instead of using an anonymous class
    addKeyListener(this);
  }

  public static void main(String[] args) {
    JFrame frame = new JFrame("KeyListener Example");
    frame.setSize(500, 500);
    frame.setResizable(false);
    frame.add(new JWindowComponent());
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }

  @Override
  public void keyPressed(KeyEvent e) {
    System.out.println("Key Pressed: " + e.getKeyChar());
  }
  
  // These two methods are required, but they can be empty
  @Override
  public void keyTyped(KeyEvent e) {}

  @Override
  public void keyReleased(KeyEvent e) {}

}

While the window has focus, you should be able to press any key and trigger the event.

Hopefully this helps.

zmehall
  • 557
  • 3
  • 13
  • okay thank i guess... gonna try it tomorrow and will share results with you... – dragon1f Sep 15 '22 at 17:43
  • well i tried it now because I couldn't resist... there is possibility I implemented it wrongly but it didn't worked as expected... (well on surface it behaved like if I did not even added anything) based on the code you shared it was supposed to output something like "Key Pressed: w" into console right? if not what am i doing wrong? – dragon1f Sep 15 '22 at 18:17
  • okay so i tried something and it seems like the "KeyListener" is not listening to keys at all... maybe... not sure about this... but it would be most sensical explanation... i am even more confused than i was before... HELP!!! – dragon1f Sep 15 '22 at 18:26
  • Did you add the listener in the constructor with `addKeyListener(this);`? As long as you do this, and the class implements `KeyListener`, you should be good. – zmehall Sep 15 '22 at 18:50
  • i can send you code via discord or telegram but i swear that i did put both in... and that is why i am so confused... it should work but doesn't... i might put them in wrong places but i bet i didn't... – dragon1f Sep 15 '22 at 19:57
  • okay i have an new information: so today i tried to run keylistener without graph rendering and it worked... but as soon as i added graph rendering it just broke... soo... what am i doing wrong??? – dragon1f Sep 16 '22 at 08:55