Results 1 to 2 of 2
  1. #1
    Join Date
    Aug 2007
    Rep Power

    Question Default Focus in JOptionPane Dialog

    When I run function showPasswordDialog(...) then default focus is OK button where as I want default focus password text field.

    Please see the comment = //DOES NOT WORK
    Kindly modify my code such that it works properly.

    Java Code:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    class TestShowPwdDialog {
         * Prompts the user for input a password with icon in a blocking dialog where the initial value, dialog title canbe specified.
         * User can input password which is required for further processing, usually by means of a <code>JTextField</code>.
         * <code>initalValue</code> is the initial value that can be used in cased of Saved Password
         * @return user's input password, or <code>null</code> meaning the user canceled the input
        public static String showPasswordDialog(Frame owner,String message,String initialValue,String title) {
            final JPasswordField pField = new JPasswordField(20);
            GridBagLayout gridbag = new GridBagLayout();
            GridBagConstraints c = new GridBagConstraints();
            final JPanel pPanel;
   = 4;
            c.insets.bottom = 4;
            pPanel = new JPanel(gridbag);
            pPanel.setBorder(BorderFactory.createEmptyBorder(10, 20, 5, 20));
            c.anchor = GridBagConstraints.WEST;
            pPanel.add(new JLabel(message),c);
            pField.addFocusListener(new FocusListener() {
            	public void focusLost(FocusEvent fe) {
            	public void focusGained(FocusEvent fe) {
            pPanel.requestFocusInWindow(); //DOES NOT WORKS
            int result = JOptionPane.showConfirmDialog(owner, pPanel,title,JOptionPane.OK_CANCEL_OPTION);
            if (result == JOptionPane.OK_OPTION)
                return String.valueOf(pField.getPassword());
            return null;
        public static void main(String []args) {
    	System.out.println(showPasswordDialog(null,"Enter user password:",null,"User Password"));

  2. #2
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Colombo, Sri Lanka
    Blog Entries
    Rep Power

Similar Threads

  1. Default Focus in JOptionPane Dialog
    By Gajesh Tripathi in forum AWT / Swing
    Replies: 5
    Last Post: 11-11-2009, 03:59 PM
  2. Replies: 0
    Last Post: 04-04-2008, 12:15 AM
  3. JOptionPane dialog (Localizing)
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 03-14-2008, 12:36 PM
  4. JOptionPane - message dialog
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 12-17-2007, 10:11 AM
  5. JOptionPane - input dialog
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 12-17-2007, 10:09 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts