Results 1 to 6 of 6
  1. #1
    Join Date
    Aug 2007
    Posts
    45
    Rep Power
    0

    Default 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;
            
            c.insets.top = 4;
            c.insets.bottom = 4;
    	pField.setText(initialValue);
            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) {
            		pField.setBackground(Color.white);
            	}
            	public void focusGained(FocusEvent fe) {
            		pField.setBackground(Color.yellow);
            	}
            });
            c.gridy=1;
            pPanel.add(pField,c);
            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
    Join Date
    Aug 2007
    Posts
    45
    Rep Power
    0

    Arrow

    Eranga wrote:
    Please don't post the same thread multiple times. I've close this.
    SORRY! Due to network failure for some moment on my system, I could not predict that my thread already has been post. So I post it again. Dear Eranga, kindly delete the same thread that has been closed by you (if possible).

    My question (using this thread) is that how to change default focus behaviour of dialog that is displayed using JOptionPane.showMessageDialog(...) function? Thanks.
    This thread is continue from my previous thread JPasswordTextField using JOptionPane

  3. #3
    zweibieren is offline Senior Member
    Join Date
    Aug 2009
    Location
    Pittsburgh, PA
    Posts
    284
    Rep Power
    6

    Default

    A little looking around reveals that
    JOptionPanel is NOT intended for displaying a password prompt.

    A lot of poking around and experimental coding shows that
    one can get the desired result:
    Java Code:
    	JButton okButton = new JButton("OK") {
    	@Override
    	public void requestFocus() {  
    			pPanel.requestFocusInWindow();
    		}
    	};		
    	Object[] possibleValues = {okButton, "Cancel"};
    	Object selectedValue = JOptionPane.showOptionDialog(null,
    		pPanel, "Input Password",
    		JOptionPane.OK_CANCEL_OPTION,
    		JOptionPane.QUESTION_MESSAGE, null,
    		possibleValues, null);

  4. #4
    zweibieren is offline Senior Member
    Join Date
    Aug 2009
    Location
    Pittsburgh, PA
    Posts
    284
    Rep Power
    6

    Default

    Yet more looking around found Java bug 4813436.
    It reveals the undocumented fact that
    Java Code:
    Object[] possibleValues = {okButton, "Cancel"};
    displays an OK button that does nothing when clicked.

    Yet further experimentation revealed the power of
    subclassing JOptionPane instead of using one of the static methods.
    The final breakthrough was to note that pField should get input focus instead of pPanel.

    The following actually works.
    Java Code:
    	 JOptionPane pane = new JOptionPane(pPanel, 
    			 JOptionPane.QUESTION_MESSAGE,
    			 JOptionPane.OK_CANCEL_OPTION)  {
    		@Override
    		 public void selectInitialValue() {
    			 pField.requestFocusInWindow();  // (not pPanel)
    		 }
    	 };
    	 pane.createDialog(null, title).setVisible(true);
    
    	 Object selectedValue = pane.getValue();
    	 if (selectedValue == null)
    		 return null;
    	 int choice = ((Integer)selectedValue).intValue();
    	 System.out.println("Selected: "+choice);
    	 if (choice == JOptionPane.OK_OPTION) {
    		 char [] pw =  pField.getPassword();
    		 System.out.print("Password: ");
    		 for (char ch : pw)
    			 System.out.print(ch);
    		 System.out.println();
    		 // getPassword() recommends clearing the password after use
    		 // of course, in this demo it has not yet been "used"
    		 for (int cx = 0; cx < pw.length; cx++)
    			 pw[cx] = 0;
    	 }

  5. #5
    Join Date
    Aug 2007
    Posts
    45
    Rep Power
    0

    Smile [solved]

    Thanks zweibieren
    Problem is solved using idea following given by you...
    Java Code:
    JButton okButton = new JButton("OK") {
    	@Override
    	public void requestFocus() {  
    			pPanel.requestFocusInWindow();
    		}
    	};
    Thank you very much...

    My modified code is pasted here. Following two things should be noted:-
    1. If we use above idea then we are not allowed to get focus on ok button
      To allow this we modify it as follow:-
      Java Code:
      JButton okButton = new JButton("OK") {
          boolean firstTimeFocuss=true;
          @Override
          public void requestFocus() {
              if(firstTimeFocuss) {
      	pPanel.requestFocusInWindow();
                  firstTimeFocuss=false;
              }		   			
              super.requestFocus();
          }
      };
      But your following logic is great:-
      JOptionPane pane = new JOptionPane(pPanel,
      JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION) {
      @Override
      public void selectInitialValue() {
      pField.requestFocusInWindow(); // (not pPanel)
      }
      };

    1. We need to use dispose dialog manually ohterwise application will not be terminated if you run this program (I run it in JCreator)


    here is source code:-
    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;
            
            c.insets.top = 4;
            c.insets.bottom = 4;
    	pField.setText(initialValue);
            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) {
            		pField.setBackground(Color.white);
            	}
            	public void focusGained(FocusEvent fe) {
            		pField.setBackground(Color.yellow);
            	}
            });
            
            c.gridy=1;
            pPanel.add(pField,c);
            pPanel.requestFocusInWindow(); //DOES NOT WORKS
            JButton okButton = new JButton("OK") {
    			boolean firstTimeFocuss=true;
    			@Override
    			public void requestFocus() {
    		   		if(firstTimeFocuss) {
    		   			pPanel.requestFocusInWindow();
    		   			firstTimeFocuss=false;
    		   		}		   			
    		   		super.requestFocus();
    		   	}
    		};
           Object[] possibleValues = {okButton, "Cancel"};
            JOptionPane pane=new JOptionPane(pPanel, JOptionPane.QUESTION_MESSAGE);
            pane.setOptions(possibleValues);
            
            final JDialog jd=pane.createDialog(owner,title);
    		pField.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent ae)	 {
    				jd.setVisible(false)	;
    			}
    		});
    		okButton.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent ae) {
    				jd.setVisible(false);
    			}		
    		});
    		jd.setVisible(true);
           Object selectedValue = pane.getValue();
           /*if(selectedValue!=null)
           		System.out.println (selectedValue+"="+selectedValue.getClass());*/
            jd.dispose();
            //int result = JOptionPane.showConfirmDialog(owner, pPanel,title,JOptionPane.OK_CANCEL_OPTION);        
            if (selectedValue!=null && selectedValue.equals("uninitializedValue"))
                return String.valueOf(pField.getPassword());
            return null;
        }
        public static void main(String []args) {
        	//arguments are: owner,message,initialValue,title
    		System.out.println(showPasswordDialog(null,"Enter user password:",null,"User Password"));
       }
    }
    Above code should be modify such that "pField should get input focus instead of pPanel" and "getPassword() recommends clearing the password after use" as suggested by zweibieren.

  6. #6
    zweibieren is offline Senior Member
    Join Date
    Aug 2009
    Location
    Pittsburgh, PA
    Posts
    284
    Rep Power
    6

    Default

    Please accept my apologies for sending you down a wrong path.
    My more recent post--overriding JOptionPane.selectInitialValue()--would have been briefer.
    Even better would have been to use JDialog directly.

Similar Threads

  1. Replies: 1
    Last Post: 03-10-2009, 02:12 PM
  2. Replies: 0
    Last Post: 04-04-2008, 01: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
  •