Userset Keybind For Java

76 Views Asked by At

So, I am making a application, when you click a button (jButton1) it prints "Hi" (for example)

Now, I also have a textbox. In the textbox you need to specify a key.

How do I make so when you press the key you specified, it runs jButton1.doClick()

UPDATE: This is a auto clicker. So, I have a boolean started If I type k (out of the application) I want it to set the boolean started to true. If I type k again, and boolean started is true, set it to false.

Thank you so much!

UPDATE 2: I really need help! Why won't String code = NativeKeyEvent.getKeyText(nativeEvent.getKeyCode()); if (code == AutoClickFrame.jTextField1.getText().toUpperCase()) { System.out.println("Hello World!"); } work?

1

There are 1 best solutions below

7
On

How do I make so when you press the key you specified, it runs jButton1.doClick()

You use Key Bindings. That is you map a KeyStroke to an Action. When the key is pressed the Action is invoked. The Action would also be used as the ActionListener of the button.

Read the section from the Swing tutorial on How to Use Key Bindings for more information.

For a working example check out: Attaching A Single Action Listener To All Buttons