を
あなたはこれを読むことをお勧めします
JOptionPane
を使用して、ユーザーとして空白を表示するJPasswordField
を表示するソリューションです タイプ。
コードに入れたいのは、showPasswordPrompt()
メソッドですが、コードにはmain()
メソッドが含まれているため、ダイアログの外観を簡単にテストできます。
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
public class JOptionPaneTest
{
public static String showPasswordPrompt(Component parent, String title)
{
// create a new JPasswordField
JPasswordField passwordField = new JPasswordField();
// display nothing as the user types
passwordField.setEchoChar(' ');
// set the width of the field to allow space for 20 characters
passwordField.setColumns(20);
int returnVal = JOptionPane.showConfirmDialog(parent, passwordField, title, JOptionPane.OK_CANCEL_OPTION);
if (returnVal == JOptionPane.OK_OPTION)
{
// there's a reason getPassword() returns a char[], but we ignore this for now...
// see: http://stackoverflow.com/questions/8881291/why-is-char-preferred-over-string-for-passwords
return new String(passwordField.getPassword());
}
else
{
return null;
}
}
public static void main(String[] args)
{
final JFrame frame = new JFrame();
final JButton button = new JButton("Push Me For Dialog Box");
button.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
String password = showPasswordPrompt(frame, "Enter Password:");
button.setText(password);
}
});
frame.add(button);
frame.setSize(400, 400);
frame.setVisible(true);
}
}
ユーザーが入力した文字は、テキストフィールドに表示されません。それは空白のままですか? – Adam
ユーザーを混乱させないように注意してください。入力を開始すると、ユーザーは何らかのフィードバックを期待します。フィードバックが表示されないボックスを使用すると、混乱する可能性があります。 – BlueFish