问题
I want to display a mask in a text field. How can I do that? Is there any reusable java library to do that? I want to create a text field that only allow to enter eight digits (each digit should be either 0 or 1)
E.g.

回答1:
This will create a masked text field. When you press enter it will output what the user typed in. This uses JPasswordField. http://docs.oracle.com/javase/1.4.2/docs/api/javax/swing/JPasswordField.html
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PasswordField1 extends JApplet implements ActionListener {
/* Declaration */
private JPasswordField Input;
private JTextField Echo;
private Container Panel;
private LayoutManager Layout;
public PasswordField1 () {
/* Instantiation */
Input = new JPasswordField ("", 20);
Layout = new FlowLayout ();
Panel = getContentPane ();
/* Location */
Panel.setLayout (Layout);
Panel.add (Input);
/* Configuration */
Input.addActionListener (this);
}
public void actionPerformed (ActionEvent e) {
char [] Chars;
String Word;
Chars = Input.getPassword();
Word = new String(Chars);
System.out.println("You Entered: " + Word);
}
}
来源:https://stackoverflow.com/questions/9995383/how-to-display-a-mask-in-jtextfield