aze45sq6d
aze45sq6d

Reputation: 925

Multiple keybindings on one key?

I am making a piano with JFrame but I have a little problem. I want the key of the piano to turn green when it's pressed, and a note to play.

b.getInputMap(JButton.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke('q'), "playD");
b.getActionMap().put("playD", playC);      //playC refers to another Action class       

b.getInputMap(JButton.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke('q'), "SetBg");
b.getActionMap().put("SetBg", db);  //db refers to another Action class

However, these methods override eachother. Right now, only the colour changes, and the note isn't played. If I remove the "SetBg" method, the note does play.

Is there any way to fix this?

A second problem I have is that I can't seem to get it to work to know when a key is actually released again. I tried .put(Keystroke.getKeyStroke("released q"), "DoSomething"); But that doesn't seem to do anything.

Thanks in advance!

Upvotes: 1

Views: 296

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

I'm not an expert on this, but I don't think that you can add two key bindings on the same key stroke without the 2nd binding blocking the first and all previous bindings. In other words, I believe that only a single binding is possible for each specific keystroke and input map.

Having said that, I'd do this differently:

  • I'd structure my program to conform to one of the Model-View-Control (MVC) design pattern standards.
  • I'd have my binding be part of the Control,
  • The Action's only function will be to change the Model's state, here being that the something key has been pressed or released.
  • The Model can have many View listeners, and they can all respond as they see fit to the change in the model's state, and here is where I'd have my two different responses to the Model's change be located.

Upvotes: 1

Related Questions