The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.swing.text  [49 examples] > JTextField  [3 examples]

e979. Creating a JTextField Component

When the user hits RETURN, the text field fires an action event.
    // Create a text field with some initial text
    JTextField textfield = new JTextField("Initial Text");
    
    // Create a text field with some initial text and a default number of columns.
    // The number of columns controls the preferred width of the component;
    // each column is rougly the size of an M in the current font.
    int cols = 30;
    textfield = new JTextField("Initial Text", cols);
    
    // Listen for action events, which are fired when the user hits RETURN
    textfield.addActionListener(new MyActionListener());
    
    class MyActionListener implements ActionListener {
        public void actionPerformed(ActionEvent evt) {
            JTextField textfield = (JTextField)evt.getSource();
            process(textfield.getText());
        }
    }

 Related Examples
e980. Creating a Password JTextField Component
e981. Aligning the Text in a JTextField Component

See also: Actions and Key Bindings    Caret and Selection    Events    JEditorPane    JFormattedTextField    JTextArea    JTextComponent    JTextPane    Styles   


© 2002 Addison-Wesley.