Ask Questions?

View Latest Questions


 
 

JTextField
Posted on: July 22, 2006 at 12:00 AM
javax.swing.JTextField has two uses.

Java: JTextField

Description

javax.swing.JTextField has two uses.

  • Input. The user can enter one line of text (a String)
  • Output. To display one line of text.

If you need a component that displays or allows entry of more than one line, use a JTextArea.

Overview of methods

JTextField
JTextField(width)
setText(text)
StringgetText()
addActionListener(listener)
setEditable(true/false)
setFont(font)
setHorizontalAlignment(align)
requestFocus(align)

To use a JTextField for Input

  1. Declare a JTextField as an instance variable. Reason: If it's an instance variable, it can be seen in all methods in the class.
  2. Assign an initial value to this variable by calling the JTextField constructor. Specify the approximate field width in the constructor. Example:
    JTextField yourInpuFieldt = new JTextField(16);
  3. Add the text field to a container.
    content.add(yourInputField);
    or to add it to a JPanel p
    p.add(yourInputField);
  4. Input is done by calling the getText().
    1. Get the string in the text field by calling yourTextField.getText() method whenever you need it. This is probably the most common way.
      String x = yourInputField.getText();
    2. Attach an action listener to the text field. It is called whenever the user types Enter in that field. The listener can then get the text and process it.