0

Hello, I am having trouble with EventHandling in JavaFX. I am in the process of making a rhythm game, and I am trying to detect user key presses. There are 4 the user is supposed to input. The keys I am trying to detect are the D, F, J, K keys. I have coded them as four Buttons (b0, b1, b2, b3 respectively), and declared 4 booleans corresponding to each of the buttons.

    b0.setOnKeyPressed(new EventHandler<KeyEvent>() {

        @Override
        public void handle(KeyEvent event) {
            if(event.getCode() == KeyCode.D) {
                dPressed = true;
            }
        }
    });

    b0.setOnKeyReleased(new EventHandler<KeyEvent>() {

        @Override
        public void handle(KeyEvent event) {
            if(event.getCode() == KeyCode.D) {
                dPressed = false;
            }
        }
    });

With this code, I intend to use the booleans to check if the user presses one of the keys at a particular time. Eclipse is giving me the error saying that dPressed must be final or effectively final.

  • Why do you need the Button class? – zlakad Dec 08 '17 at 05:00
  • Possible duplicate of [Problems with local variable scope. How to solve it?](https://stackoverflow.com/questions/25894509/problems-with-local-variable-scope-how-to-solve-it) – Muzib Dec 08 '17 at 05:08
  • I plan on creating graphics to map to the buttons, since I found that the Button constructor had a Graphics parameter. What I want is in the client, when the user inputs one of the assigned buttons, the corresponding Button would change color, and allow me to detect their input. Since you are question Button's use, I assume I am going about it incorrectly. So would you mind pointing me in the right direction? – ferrarellij Dec 08 '17 at 05:14
  • You can (and should) use some other control instead of Button. Almost every control (if not all of them) can change the color. Try to bind your event (onKeyPressed, onKeyReleased...) to the container. – zlakad Dec 08 '17 at 05:21
  • Ah, I see. Thank you, and I will do that and see how that goes. – ferrarellij Dec 08 '17 at 05:28

0 Answers0