Java JPasswordField set text

Description

Java JPasswordField set text


import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;

public class Main extends JFrame {
  JPasswordField passwordField; // password field with text

  public Main() {
    super("Testing");
    setLayout(new FlowLayout());
    // construct password field with default text
    passwordField = new JPasswordField("Hidden text");
    add(passwordField); // add passwordField to JFrame

    // register event handlers
    TextFieldHandler handler = new TextFieldHandler();

    passwordField.addActionListener(handler);
  } // end Main constructor

  // private inner class for event handling
  private class TextFieldHandler implements ActionListener {
    @Override/*  w w w .j ava  2 s  .  c  o m*/
    public void actionPerformed(ActionEvent event) {
      String string = "";

      // user pressed Enter in JTextField passwordField
      if (event.getSource() == passwordField)
        string = String.format("passwordField: %s", event.getActionCommand());

      // display JTextField content
      JOptionPane.showMessageDialog(null, string);
    }
  } // end private inner class TextFieldHandler

  public static void main(String[] args) {
    Main Main = new Main();
    Main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Main.setSize(350, 100);
    Main.setVisible(true);
  }
}



PreviousNext

Related