Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9053081
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T13:20:18+00:00 2026-06-16T13:20:18+00:00

I have the following code: JTextField uname = new JTextField(defaultUser); JPasswordField passwd = new

  • 0

I have the following code:

JTextField uname = new JTextField(defaultUser);
JPasswordField passwd = new JPasswordField();
JTextField serverAddress = new JTextField(defaultServer);
JTextField port = new JTextField(Integer.toString(defaultPort));
final JComponent[] inputs = new JComponent[]{new JLabel("Username"), uname, new JLabel("Password"), passwd, new JLabel("Server Address"), serverAddress, new JLabel("Server Port"), port};


int var = JOptionPane.showConfirmDialog(parent, inputs, "Enter Connection Details", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (var != 0) {
    return;
}
....

This creates a dialog box that prompts for some details to connect to a server. What I’d like is to make the password field the default selected. That is, the cursor is there by default so you can start typing it as soon as the pane appears, as opposed to having to select the password box first – By default, the OK button has focus.

I’ve tried with passwd.requestFocusInWindow() but it doesn’t work (because I think that the box has to be visible before calling that for it to work). I also tried overriding passwd’s requestFocus method with various content, but it didn’t fly either (probably because it’s not getting called anyway….)

Note: I know that some of the other JOptionPane methods have default value parameters, but they have issues laying out the input boxes, so they’re no good to me.

Anyone got any ideas? It’s not a deal breaker, so I won’t be too upset if it can’t be done easily.

Cheers

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T13:20:19+00:00Added an answer on June 16, 2026 at 1:20 pm

    Try adding a ComponentListener to the password field, and when it becomes visible then invoke #requestFocusInWindow

    Update:
    JOptionPane makes the [OK] button default in the dialog and focuses it when the dialog is shown. So the solution is not that obvious… we have to add a HierarchyListener and wait until the password field is added to dialog, then check if the dialog’s JRootPane have a default button and if so add a FocusListener, finally when the button gets permanent focus switch focus to the password field:

    import static javax.swing.JOptionPane.OK_CANCEL_OPTION;
    import static javax.swing.JOptionPane.PLAIN_MESSAGE;
    
    import java.awt.event.FocusAdapter;
    import java.awt.event.FocusEvent;
    import java.awt.event.HierarchyEvent;
    import java.awt.event.HierarchyListener;
    
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPasswordField;
    import javax.swing.JRootPane;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    
    public class FocusPasswordFieldInOptionPaneDemo implements Runnable
    {
        public static void main(String[] args)
        {
            SwingUtilities.invokeLater(new FocusPasswordFieldInOptionPaneDemo());
        }
    
        @Override
        public void run()
        {
            JTextField uname = new JTextField("user");
            JPasswordField passwd = new JPasswordField();
            JTextField serverAddress = new JTextField("server");
            JTextField port = new JTextField(Integer.toString(1337));
            final JComponent[] inputs = new JComponent[] {new JLabel("Username"), uname, new JLabel("Password"), passwd,
                    new JLabel("Server Address"), serverAddress, new JLabel("Server Port"), port};
    
            makeSurePasswordFieldGetsFocus(passwd);
    
            int answer = JOptionPane.showConfirmDialog(null, inputs, "Enter Connection Details", OK_CANCEL_OPTION, PLAIN_MESSAGE);
            System.out.println(answer);
        }
    
        /**
         * {@link JOptionPane} makes the [OK] button default in the dialog and makes it focused.
         * <p>
         * So via a couple of listeners we can wait until the button gets permanent focus and then switch focus to the password field.
         */
        private void makeSurePasswordFieldGetsFocus(final JPasswordField passwd)
        {
            passwd.addHierarchyListener(new HierarchyListener()
            {
                HierarchyListener hierarchyListener = this;
    
                @Override
                public void hierarchyChanged(HierarchyEvent e)
                {
                    JRootPane rootPane = SwingUtilities.getRootPane(passwd);
                    if (rootPane != null)
                    {
                        final JButton okButton = rootPane.getDefaultButton();
                        if (okButton != null)
                        {
                            okButton.addFocusListener(new FocusAdapter()
                            {
                                @Override
                                public void focusGained(FocusEvent e)
                                {
                                    if (!e.isTemporary())
                                    {
                                        passwd.requestFocusInWindow();
                                        passwd.removeHierarchyListener(hierarchyListener);
                                        okButton.removeFocusListener(this);
                                    }
                                }
                            });
                        }
                    }
                }
            });
        }
    }
    

    This solution works but it’s a bit hacky… An alternative is to create a custom “DatabaseConnectionDialog”, something like @syb0rg’s answer.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following code adding an ActionListener to a JTextField: chatInput.addMouseListener(new java.awt.event.MouseAdapter() {
I have the following code: InputStream reportFile = MyPage.this.getClass().getResourceAsStream(test.jrxml); HashMap<String, String> parameters = new
I have the following code: var tf:TextFormat = new TextFormat(); tf.font = arial; aRButton.textField.antiAliasType
I have the following code: public test() { setLayout(new FlowLayout()); JFormattedTextField price = new
I have following Java code: JFrame frame = new JFrame(); frame.setTitle(Sudoku); frame.setLocationRelativeTo(null); frame.setSize(500, 500);
I have following code in initialization im = imread('Image02.tif'); figure(); imagesc(im); colormap(gray); [hImage hfig
I have following code <div id=main> <div id=one> </div> <div id=two> </div> <div id=three>
I have following code for updating user's column public void UpdateLastModifiedDate(string username) { using
I have following code for loading image from url in xml parsing endElement method
I have following code for inserting data into database using PDO. It inserts data

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.