सबसे आसान काम JOptionPane
के showConfirmDialog
विधि का उपयोग करने के लिए और एक JPasswordField
के लिए एक संदर्भ में पारित करने के लिए है, जैसे
JPasswordField pf = new JPasswordField();
int okCxl = JOptionPane.showConfirmDialog(null, pf, "Enter Password", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (okCxl == JOptionPane.OK_OPTION) {
String password = new String(pf.getPassword());
System.err.println("You entered: " + password);
}
संपादित
नीचे JPasswordField
के साथ एक संदेश प्रदर्शित करने के लिए कस्टम JPanel
का उपयोग कर एक उदाहरण है। सबसे हाल ही में टिप्पणी के अनुसार, मैं भी है (जल्दी से) जब संवाद पहले प्रदर्शित किया जाता है JPasswordField
फोकस हासिल करने के लिए अनुमति देने के लिए कोड जोड़ा।
public class PasswordPanel extends JPanel {
private final JPasswordField passwordField = new JPasswordField(12);
private boolean gainedFocusBefore;
/**
* "Hook" method that causes the JPasswordField to request focus the first time this method is called.
*/
void gainedFocus() {
if (!gainedFocusBefore) {
gainedFocusBefore = true;
passwordField.requestFocusInWindow();
}
}
public PasswordPanel() {
super(new FlowLayout());
add(new JLabel("Password: "));
add(passwordField);
}
public char[] getPassword() {
return passwordField.getPassword();
}
public static void main(String[] args) {
PasswordPanel pPnl = new PasswordPanel();
JOptionPane op = new JOptionPane(pPnl, JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
JDialog dlg = op.createDialog("Who Goes There?");
// Wire up FocusListener to ensure JPasswordField is able to request focus when the dialog is first shown.
dlg.addWindowFocusListener(new WindowAdapter() {
@Override
public void windowGainedFocus(WindowEvent e) {
pPnl.gainedFocus();
}
});
if (op.getValue() != null && op.getValue().equals(JOptionPane.OK_OPTION)) {
String password = new String(pPnl.getPassword());
System.err.println("You entered: " + password);
}
}
}
JPasswordField की तरह कुछ के साथ इसे बंद करने के लिए (10) को स्वीकार नहीं करता की आवश्यकता होगी पासवर्ड लंबे समय तक 10. इसे अधिक व्यापक बनाने के लिए बेहतर या नीचे @Adamski जैसे नो-एर्ग कन्स्ट्रक्टर का उपयोग करें। इसके अलावा भी डिफ़ॉल्ट विकल्प होना चाहिए क्योंकि कई उपयोगकर्ता अपना पासवर्ड टाइप करने के बाद एंटर हिट से बाहर होंगे। अगर रद्द करना डिफ़ॉल्ट है तो प्रवेश के बाद पासवर्ड टाइप करना सिर्फ संवाद रद्द कर देगा। – gb96
यह एक अच्छा एक है, JOptionPane में और उसके स्वीकार करने पासवर्ड मेरे मामले में एक JPasswordField साथ एक लेबल से अधिक समय से 10 –
कैसे आप जब संवाद प्रकट होता है फोकस पासवर्ड क्षेत्र देते है? – mjaggard