Search code examples
javaswingcursorjtextfield

setting cursor to JTextfield


im trying to get the cursor to move to a textfield when a specific key is pressed like when you press tab. im trying to do this instead of just using tab because i want to implement other actions at the same time, how do i do this?

here is the key event for keypressed so far

Fname.addKeyListener(new KeyListener(){

        @Override
        public void keyPressed(KeyEvent e) {
            // TODO Auto-generated method stub
            if(e.getKeyCode() == KeyEvent.VK_TAB){
                Sname.setFocusable(true);
                Sname.getFocusAccelerator();

                if(Sname.hasFocus()){
                    Sname.setText("");
                }
            }   
            //System.out.print(e + "keyRelease: ");
        }

any help would be greatly appreciated thank you for your time


Solution

  • i want to implement other actions at the same time

    Don't use a KeyListener. Swing was designed to use Key Bindings.

    See Key Bindings for more information and a link to the Swing tutorial on the same topic.