简体   繁体   中英

Display message in TextArea when tab presed in TextField in java

The following code was supposed to make the program detect when tab is pressed in a certain JTextField (called timeStep) and display a message in a TextArea (called textAreaInsructions), but it doesn't seem to work. Can anyone please tell me why?

timeStep.setFocusTraversalKeys(
                KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, Collections.EMPTY_SET);

        timeStep.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent evt) {
                if(evt.getKeyCode() == KeyEvent.VK_TAB){
                    instruction = "Enter a real number time step";
                    textAreaInstructions.setText(instruction);
                    /* If you want to change the focus to the next component */
                    //nextJComponent.grabFocus();
            }
            }
        });

The TAB key is already eaten by most swing components, since it is tied to the field focus control. There's more than one way to handle it, you can try alternatives:

Instead of explicity listening for the TAB key, you can use a FocusListener to simply detect when the focus leaves the text field.

or

Register a keyboard action: JComponent.registerKeyboardAction(action, keystroke, WHEN_IN_FOCUSED_WINDOW); for the TAB key.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM