Search code examples
javaswingmouseeventjtextfieldkeyboard-events

Mouse cursor change once ENTER pressed


I have an image here to explain my query enter image description here

As you can see in the image I have many text fields,right now the cursor is on the text field(the cursor could be on any textfield). As you can 3 out of the last 4 fields are disabled,once I press the enter those get enabled.This everything works fine. My query is once I press enter how do I move my cursor to the position down there(marked in red)? This is the small snippet of code for the once enter key pressed.

((JPanel)frame.getContentPane()).getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke("ENTER"), "doSomething");
        ((JPanel)frame.getContentPane()).getActionMap ().put("doSomething", new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                System.out.println("profit");
                // disabledField.setEnabled(true);
                textbox9.setEnabled(true);
                textbox10.setEnabled(true);
                textbox11.setEnabled(true);
            }
        });

Solution

  • You can request focus by using JComponent#requestFocusInWindow

    For example...

    public void actionPerformed(ActionEvent arg0) {
        System.out.println("profit");
        // disabledField.setEnabled(true);
        textbox9.setEnabled(true);
        textbox10.setEnabled(true);
        textbox11.setEnabled(true);
        textbox9.requestFocusInWindow();
    }
    

    Take a look at How to use the Focus Subsystem for more details