Reputation: 148
I have a GUI window with several components. Some of them are buttons to which I added keyboard shortcuts. For example, a certain button can be triggered by pressing "a" anywhere in the window. One of the components in a JTextArea. Now, when the focus is in the textarea, and the user types, e.g., "aha" into the JTextArea, the button is triggered twice (in addition to the text "aha" being added to the text area). How can I turn this off? I want the JTextArea to consume the "a" event, so that it does not also trigger the button.
What I want: if an "a" is typed anywhere in the window except in the JTextArea, I want my button to be triggered. But I don't want the button to be triggered while the JTextArea is in focus and the user is typing into the JTextArea.
What I already tried: I tried adding a KeyListener to the JTextArea, which intercepts and consumes any key that is typed. But it had the opposite effect: the button is still triggered, but the letter is not added to the JTextArea.
Here is a minimal example:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
// Create a simple GUI window
public class Gui
{
private static void createWindow()
{
// Create a frame.
JFrame frame = new JFrame("Simple");
// Add a
// Add a text area.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextArea textarea = new JTextArea();
textarea.setPreferredSize(new Dimension(300, 100));
frame.getContentPane().add(textarea, BorderLayout.CENTER);
// Add a button.
JButton button = new JButton();
button.setText("Button");
button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.get\
KeyStroke(KeyEvent.VK_A, 0), "key");
Action action = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
System.out.println("Action!");
button.doClick();
}
};
button.getActionMap().put("key", action);
frame.getContentPane().add(button, BorderLayout.LINE_END);
frame.pack();
frame.setVisible(true);
}
public static void main(String args[])
{
System.out.println("Hello, World");
createWindow();
}
}
Upvotes: 0
Views: 783
Reputation: 324118
The JTextArea listens for keyTyped
events. You are adding a binding for keyPressed
.
If you instead create the binding for keyTyped
event then the text area will handle the event:
//button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "key");
button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("typed a"), "key");
Upvotes: 1