I've been trying to make a JTextArea display a certain String when F2 is pressed in a certain TextField, with no success as yet. Any help much appreciated.
My code may reveal how little programming experience I have:
final String ACTION_KEY = "this text";
public void actionPerformed(ActionEvent actionEvent) {
JTextField source = (JTextField) actionEvent.getSource();
System.out.println("Activated: " + source.getText());
textAreaInstructions.setText("this text");
}
};
KeyStroke F2 = KeyStroke.getKeyStroke("F2");
InputMap inputMap = timeStep.getInputMap();
inputMap.put(F2, ACTION_KEY);
ActionMap actionMap = timeStep.getActionMap();
actionMap.put(ACTION_KEY, actionListener);
EDIT: I'm now trying this code instead:
InputMap inputMap = timeStep.getInputMap();
Object actionSubmit = inputMap.get(KeyStroke.getKeyStroke("ENTER"));
Object actionSubmitSp = inputMap.get(KeyStroke.getKeyStroke("SPACE"));
System.out.println("actionSubmit for space = " + actionSubmitSp);
ActionMap actionMap = timeStep.getActionMap();
Action action = actionMap.get(actionSubmit);
System.out.println("actionSubmit = " + actionSubmit);
timeStep.getInputMap().put(KeyStroke.getKeyStroke("SPACE"),
actionSubmit);
EDIT:
This prints
actionSubmit for space = null
actionSubmit = notify-field-accept
Is this any use?
The problem was nothing to do with the code posted. It was that I'd saved a backup of the file in the same package as the original and forgot to change the code, so the backup was being implemented rather than the updated original. That cost me a lot of time. lol.
EDIT: so anyway, now that I know which file I'm running, I found that the following code (which I got here: http://blog.marcnuri.com/blog/.../2007/06/06/Detecting-Tab-Key-Pressed-Event-in-JTextField-s-Event-VK-TAB-KeyPressed ) does what I wanted (for tab instead of F2, but would obviously work for F2 too, in which case the first line wouldn't be needed):
timeStep.setFocusTraversalKeys(
KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, Collections.EMPTY_SET);
timeStep.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_TAB){
instruction = "tab pressed";
textAreaInstructions.setText(instruction);
lblTabEvent.setText(instruction);
// If you want to change the focus to the next component
timerInterval.grabFocus();
}
else {
textAreaInstructions.setText("got here, "+ e.getKeyCode());
}
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.