Search code examples
javaswingjtextfield

How to automatically focus JTextField?


Right now im making a small commander with a JTextField as inputField. How do I automatically focus this when the window opens?

There is nothing else to do than inserting something into the field and pressing Enter at the end.


Solution

  • You need:

    JFrame frame = new JFrame();
            JTextField text = new JTextField();
            frame.add(text);
            frame.addWindowListener(new WindowAdapter() {
                @Override
                public void windowOpened(WindowEvent e) {
                    text.requestDefaultFocus();
                }
            });