Userset Keybind For Java - java

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?

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

Related

glfwGetKeyName() returns null

I'm currently working on the input system of a game engine in java, and I use GLFW for the window. I set up a callback system to catch when a key is pressed:
GLFW.glfwSetKeyCallback(window, (windowId, key, scancode, action, mods) -> {
if (action == GLFW.GLFW_PRESS) {
System.out.println(GLFW.glfwGetKeyName(key, scancode));
}
});
And the problem is when I press space or enter or shift plus a different key it prints out null. My question is: how to use the mods attribute to capitalize the next key when I press shift or print out a new line when I press enter etc.
I don't know the solution for the first question, but the second one is easy.
Try using char callback. This one is different from key callback, as it only works with unicode characters being typed by user (letters are capitalized with Shift, CapsLock button also works). Also, if you want to detect modifier buttons being pressed while user types, try using charMods callback. Seems like the latter is marked for removal, so you can test whether the modifier button is pressed with glfwGetKey().
EDIT: Seems like I didn't understood you on the first one. glfwGetKeyName() is not designed to be used as text input method. Also note that it can display names for a limited range of buttons. What is more, when you press multiple keys, press event for each one is called in separate key callback event. You can't handle multiple key presses at once. (Modifier keys are put in mods argument of callback, but I can't tell by now whether they also trigger a key press event or not - check it yourself)

Swing - Can Enter be used for focus traversal and action performed?

I understand that this is a ridiculous (and somewhat embarrassing) scenario and one which I am beginning to believe is not actually possible to overcome...
I have developed a basic swing application for my client which consists of a frame containing text fields and combo boxes which validates / processes the data captured when they lose focus - standard issue stuff.
My client is hell-bent on living in the "DOS days" by being able to traverse from field to field using the ENTER key instead of the default TAB key.
I achieved this simply and neatly by implementing KeyboardFocusManager.getCurrentKeyboardFocusManager().setDefaultFocusTraversalKeys(...). (See below for full code)
At certain points during data being captured I need to show an error or warning message and I achieve this by the obvious JOptionPane.showMessageDialog(parentComponent, message, "Warning", JOptionPane.WARNING_MESSAGE) routine.
The problem - when faced with the dialog message box, my client expects that he can then press ENTER to close it which no longer works because I have obviously overridden the actionPerformed event of ENTER and instead have assigned it as a focus traversal key.
I am aware that SPACE works perfectly instead to fire off the actionPerformed event on the Ok button which in turn merrily closes the dialog box. The issue is my client wants to be able to press ENTER...
I am trying to avoid creating a custom dialog message box but even if I attempted this I don't think I will be able to achieve the result I want because of my next point...
I have tried using JOptionPane.showOptionDialog(parentComponent, message, "Error", JOptionPane.OK_OPTION, JOptionPane.ERROR_MESSAGE, null, buttons, null) instead where buttons is an array of pre-created buttons that I can add action / key / focus listeners onto to try re-create the default behaviour of the ENTER key. The problem is that ENTER no longer registers at all in any of these event listeners as long as I am assigning it as a focus traversal key.
This is how I am setting ENTER (and ESC, TAB and SHIFT+TAB) as focus traversal keys:
// Enable Enter & Tab as forward traversal keys and Esc & Shift-Tab as backward traversal keys
KeyStroke esc = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
KeyStroke tab = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);
KeyStroke shiftTab = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, KeyEvent.SHIFT_DOWN_MASK);
Set<KeyStroke> forwardKeys = new HashSet<KeyStroke>();
forwardKeys.add(enter);
forwardKeys.add(tab);
Set<KeyStroke> backwardKeys = new HashSet<KeyStroke>();
backwardKeys.add(esc);
backwardKeys.add(shiftTab);
KeyboardFocusManager.getCurrentKeyboardFocusManager().setDefaultFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, forwardKeys);
KeyboardFocusManager.getCurrentKeyboardFocusManager().setDefaultFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, backwardKeys);
Any idea if this is possible or should I just tell my client to deal with it and get used to pressing SPACE?
Thanks in advance,
Xandel
try this on the okButton and enter will start working but after this tab shift+tab also won't work on button.
okButton.setFocusTraversalKeysEnabled(false);

How to recognise if shift is selected when a button is clicked on an actionPerformed (Java Swing)?

I'm trying to create a different actionPerformed when Shift is held down while pressing a JButton, but when I use:
event.isShiftDown;
my program does not compile because it does't recognise it.
Basically you need to bitwise-and the ActionEvent#getModifiers result
if ((e.getModifiers() & InputEvent.SHIFT_MASK) != 0) {
// Shift is down...
}
As an alternative to checking the event modifiers directly, consider using a different Action for each state of the shift key. You can supply the desired mask to the KeyStroke used in your key binding, as outlined here. A related example using getMenuShortcutKeyMask() is shown here.

Binding key combination to JFrame

So far I've got ESC key to close the window, using the following code:
KeyStroke escapeKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false);
Action escapeAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
screen.dispose();
}
};
screen.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escapeKeyStroke, "ESCAPE");
screen.getRootPane().getActionMap().put("ESCAPE", escapeAction);
But I am wondering how I would go about adding a CTRL+A event? I remember reading about a way where you set booleans for keypressed/released, but I don't see that working with this piece of code, so I am wondering how I can implement CTRL+A.
Thank You
It's the second parameter of the KeyStroke.getKeyStroke(...) method that matters, as you'll want to use the InputEvent.CTRL_DOWN_MASK there to let the KeyEvent.VK_A be a control-A.
e.g.,
KeyStroke ctrlAKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_A,
InputEvent.CTRL_DOWN_MASK);
I wouldn't worry about using the 3 parameter method that uses a boolean since you're more interested in key press, not key down or key release.
Regarding your comment:
Correction to my earlier comment. It works, if I make it let's say Ctrl+W. Ctrl+A just attempts to do its native "select all" function in a textfield in the frame. Any way to avoid that?
From the little I understand, this will be a problem if the component that has focus (such as a JTextArea) responds directly to the ctrl-A key press. To get around this, you can add the same binding to this component, but being sure to bind it to its InputMap that uses the JComponent.WHEN_FOCUSED; condition.

Can multiple accelerators be defined for a JMenuItem?

I've a problem with setAccelerator(). Right now, I have the code that works for Ctrl+X for DELETE operation. I want to set the accelerator to Shift+Delete as well for same JMenuItem.
My code as follows:
JMenuItem item = new JMenuItem(menuText);
item.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_X, KeyEvent.CTRL_MASK));
item.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_DELETE, KeyEvent.SHIFT_MASK));
but this is working only for Shift+Delete operation. Seems it is overriding the Ctrl+X operation. Can we make both these keystrokes work at the same time?
Please guide.
Yes it can be done. Behind the scenes the setAccelerator() is just creating a Key Binding, however as you noticed the second binding replaces the first.
So, you need to create an Action (not an ActionListener) to add the to the menu item. Read the section from the Swing tutorial on How to Use Actions for more information. Now that you have created the Action, you can share the Action with another KeyStroke by manually creating a Key Binding. You can read the section from the Swing tutorial on How to Use Key Bindings for a detailed explanation. Or you can read my blog on Key Bindings which give some simple code examples.
This second binding will not show up on the menu item itself.
From: http://java.sun.com/j2se/1.4.2/docs/api/java/awt/AWTEvent.html
The masks are also used to specify to which types of events an AWTEventListener should listen.
So you can combine the mask for two keys, but not the KeyEvents.
item.setAccelerator(
KeyStroke.getKeyStroke(
KeyEvent.VK_X, KeyEvent.CTRL_MASK + KeyEvent.SHIFT_MASK));
A workaround solution would be to catch the KeyEvent in the middle (after your component fired it, but before your listeners will act on it) and check, whether its one of the two combinations. Then fire one event, on which you programmatically agree to represent the action you wanted.
The second call indeed overrides the accelerator. If the method starts with set, there will be only one. If the method starts with add, you can have more than one (for example for a number of listeners).
If you want multiple keystrokes to do the same, I think you should add a keyListener to the top frame (or panel, dialog, ...) which invokes the action listeners added to the menuItem.

Categories