Điều đơn giản nhất là sử dụng JOptionPane
's showConfirmDialog
phương pháp và để vượt qua trong một tham chiếu đến một JPasswordField
; ví dụ.
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);
}
Sửa
Dưới đây là một ví dụ sử dụng một tùy chỉnh JPanel
để hiển thị một thông điệp cùng với JPasswordField
. Theo nhận xét gần đây nhất, tôi cũng đã (vội vàng) thêm mã để cho phép JPasswordField
lấy tiêu điểm khi hộp thoại được hiển thị lần đầu tiên.
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) không chấp nhận mật khẩu dài hơn 10. Tốt hơn để làm điều này rộng hơn nhiều hoặc sử dụng hàm tạo no-arg như @Adamski bên dưới. Đồng thời, OK nên là tùy chọn mặc định vì nhiều người dùng sẽ thoát khỏi thói quen nhấn Enter sau khi nhập mật khẩu của họ. Nếu Cancel là mặc định thì gõ mật khẩu theo sau là enter sẽ hủy bỏ hộp thoại. – gb96
cái này là tốt nhất, một nhãn với một JPasswordField trong JOptionPane và trong trường hợp của tôi nó chấp nhận mật khẩu dài hơn 10. –
Làm thế nào để bạn cung cấp cho trường mật khẩu tập trung khi hộp thoại xuất hiện? – mjaggard