This may seem trivial, but I can't figure out how to give the password box in this dialog focus.
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
public class PasswordBox {
@SuppressWarnings("unused")
public String prompt() {
JPasswordField pass = new JPasswordField(10);
int action = JOptionPane.showConfirmDialog(null, pass,"Enter Password",JOptionPane.OK_CANCEL_OPTION);
return new String(pass.getPassword());
}
}
I invoke it from other classes like this: String tmpPASS = new PasswordBox().prompt();
For some reason, when the dialog shows up, the "OK" button gets focus.
stacktrace (see Eng.Fouad's answer):
at javax.swing.JComponent.addNotify(Unknown Source)
at PasswordBox$1.addNotify(PasswordBox.java:14)
at java.awt.Container.addNotify(Unknown Source)
Check out the solution presented in Dialog Focus.
Edit:
Using the approach suggested by Eng Fouad I believe the code should be:
Edit2:
The link in the "Dialog Focus" blog entry has a comment with a suggestion that works on Linux.
The problem is that JOptionPane is completely self contained, and seems to offer no way to specify which GUI component gets the initial focus. One solution would be to write your own subclass of Dialog - that will let you control the layout exactly and set the focus appropriately.
You might also try a javax.swing.SwingWorker. You could create one of these and start it BEFORE showing the password dialog. In the doInBackground() method, sleep for a short time, in the done() method use SwingUtilties.invokeLater() and within that Runnable, issue pass.requestFocusInWindow().
or here is another way to do it:
Edit (by camickr, feel free to remove if this is not correct). I believe the code should be:
here is a working solution with focus in password field and working buttons
https://stackoverflow.com/a/21426340/2110961