Java JPasswordField handle ENTER key pressed event
import java.awt.FlowLayout; import java.util.Arrays; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JPasswordField; class Demo extends JPanel { public Demo() { setLayout(new FlowLayout()); /*w w w .j a v a2s . c o m*/ JPasswordField passwordField = new JPasswordField(10); passwordField.setActionCommand("password"); passwordField.addActionListener(e->{ String cmd = e.getActionCommand(); System.out.println(cmd); char[] input = passwordField.getPassword(); System.out.println(Arrays.toString(input)); }); add(passwordField); } } public class Main { public static void main(String[] args) { Demo panel = new Demo(); JFrame application = new JFrame(); application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); application.add(panel); application.setSize(250, 250); application.setVisible(true); } }
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//from www . j a v a 2 s. c om 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); } }