如何使用JOption窗格的showInputDialog隐藏字符。例如:JOptionPane.showInputDialog(“输入你的名字:”)。使用JOptionPane隐藏数据
我想隐藏字符,当用户给他的名字。我正在申请中。如果我可以隐藏这些角色,我的工作就完成了。我不想使用JPasswordField,因为它需要一个表单来保存该标签(JPasswordField)。
如何使用JOption窗格的showInputDialog隐藏字符。例如:JOptionPane.showInputDialog(“输入你的名字:”)。使用JOptionPane隐藏数据
我想隐藏字符,当用户给他的名字。我正在申请中。如果我可以隐藏这些角色,我的工作就完成了。我不想使用JPasswordField,因为它需要一个表单来保存该标签(JPasswordField)。
public static String getName() {
JPasswordField jpf = new JPasswordField(24);
JLabel jl = new JLabel("Enter Your Name: ");
Box box = Box.createHorizontalBox();
box.add(jl);
box.add(jpf);
int x = JOptionPane.showConfirmDialog(null, box, "Name Entry", JOptionPane.OK_CANCEL_OPTION);
if (x == JOptionPane.OK_OPTION) {
return jpf.getText();
}
return null;
}
:能否请您多说一下Box ... – user10101 2012-04-02 12:11:22
请阅读http://docs.oracle.com/javase/6/docs/api/javax/swing/Box.html – 2012-04-04 06:38:35
您可以使用JPasswordField,默认情况下用'*'替换字符。
您可能需要阅读此:
Why does JPasswordField.getPassword() create a String with the password in it?
如果你正在寻找一个替代JPasswordField中,你可能需要阅读此:
如果我使用JPasswordField,它使我创建一个form.I不想这样做,有没有办法uisng JOPtion窗格? – user10101 2012-03-29 11:27:08
@ user10101'JOptionPane'可以显示'组件',所以你不需要为了使用密码字段而创建一个'JFrame'或者一个'JDialog'(我想这就是你的意思是“form”)。 – lhballoti 2012-03-29 14:13:33
确切地说,JOptionPane可以显示组件,但我如何隐藏他在JOption窗格中输入的数据? – user10101 2012-03-30 06:32:06
下面是一个解决方案,它使用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 2012-04-02 06:31:49
只要小心,不要混淆你的用户。如果你开始打字,用户会期望得到某种反馈。有一个没有显示任何反馈的框可能会让人困惑。 – BlueFish 2012-04-08 11:19:38