Search code examples
javaswingjoptionpane

Setting focus in JOptionPane JPasswordField


I have created a password field using JOptionPane. When I run the program, the JOptionPane comes up and looks great, however the focus always goes to the OK button. I want the focus start on the password field. I've tried requestFocus(), requestFocusInWindow(), but this doesn't seem to work. Is there something special that I need to go to get the focus on password field?

See my code below :

JPasswordField pf = new JPasswordField();
pf.requestFocusInWindow();
int okCxl = JOptionPane.showConfirmDialog(null, pf, "ENTER SUPERUSER PASSWORD", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

Solution

  • You'll have to create an instance of the JOPtionPane and use the setWantsInput(boolean) method. It's not as convenient, but the builder methods you're using are really just for the basic cases. Then you'll need to add a ComponentListener to the Dialog to request selection of your password field. You can find more similar documenation on the JOptionPane javadoc.

        final JPasswordField pf = new JPasswordField();
        //Create OptionPane & Dialog
        JOptionPane pane = new JOptionPane(pf, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
        JDialog dialog = pane.createDialog("ENTER SUPERUSER PASSWORD");
        //Add a listener to the dialog to request focus of Password Field
        dialog.addComponentListener(new ComponentListener(){
    
            @Override
            public void componentShown(ComponentEvent e) {
                pf.requestFocusInWindow();
            }
            @Override public void componentHidden(ComponentEvent e) {}
            @Override public void componentResized(ComponentEvent e) {}
            @Override public void componentMoved(ComponentEvent e) {}
            });
    
        dialog.setVisible(true);