如何在jtextfield中显示掩码?

时间:2012-04-03 14:30:08

标签: java swing awt

我想在文本字段中显示蒙版。我怎样才能做到这一点?是否有可重用的java库来做到这一点?我想创建一个只允许输入八位数的文本字段(每个数字应该是0或1)

E.g。

enter image description here

1 个答案:

答案 0 :(得分:2)

这将创建一个蒙版文本字段。当您按Enter键时,它将输出用户输入的内容。这使用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);
  }
}