简体   繁体   中英

i need working input for java. scanner doesn't work so neither buffer. on idea what should i do

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM