import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SampleTextField { public static void main(String args[]) { JFrame application = new JFrame( "JTextField and JPasswordField Demonstration"); application.setLayout(new FlowLayout()); // construct textfield with default sizing JTextField textField = new JTextField(10); application.add(textField); textField.addActionListener(new TextFieldHandler("Text box #1")); // construct textfield with default text textField = new JTextField("Enter text here"); application.add(textField); textField.addActionListener(new TextFieldHandler("Text box #2")); // construct textfield with default text and // 20 visible elements and can't be modified textField = new JTextField("Uneditable text field", 20); textField.setEditable(false); application.add(textField); textField.addActionListener(new TextFieldHandler("Text box #3")); // construct textfield with default text JPasswordField passwordField = new JPasswordField("Hidden text"); application.add(passwordField); passwordField.addActionListener(new PasswordFieldHandler()); application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); application.setSize(325, 100); application.setVisible(true); } } class TextFieldHandler implements ActionListener { private String name; TextFieldHandler(String name) { this.name = name + ": "; } // process text field events public void actionPerformed(ActionEvent event) { String msg = name + event.getActionCommand(); JOptionPane.showMessageDialog(null, msg); } } class PasswordFieldHandler implements ActionListener { public void actionPerformed(ActionEvent event) { JPasswordField pwd = (JPasswordField) (event.getSource()); String msg = "passwordField: " + new String(pwd.getPassword()); JOptionPane.showMessageDialog(null, msg); } } /******************************************************************************* * Based on example code from Deitel & Associates, Inc. Prentice Hall. (2002) *******************************************************************************/