如何使用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