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.
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"));
}
}