How to Add Text to a JTextField

The JTextField is the Java Swing control that is used to represent a box of user-editable text in a Graphical User Interface (GUI). Examples of a textfield are the username and password boxes on Web pages. Normally, the text in the JTextField is typed by the user. But the programmer can add certain text to appear in the JTextField directly with Java code.

Instructions

    • 1

      Open a text editor or Java Integrated Development Environment (IDE) such as NetBeans (see Resources). Click "File" and "New." Type the following to define a simple Java program with a window and a single JTextField within it:

      import javax.swing.JFrame;

      import javax.swing.JTextField;

      public class JTextFieldTester {

      public static void main(String[] args) {

      JFrame window = new JFrame();

      JTextField tField = new JTextField();

      window.add(tField);

      window.pack();

      // The rest of the code will go after this line.

      }

      }

    • 2

      Type the following into the main method after the indicated line:

      tField.setText("Type something here.");

      This will make it so that the program begins with the text "Type something here" inside the JTextField.

    • 3

      Save your work.

Tips & Warnings

  • A nifty trick you can try is adding text to that which is already in the JTextField, so that the two texts are combined. Type the following to achieve that effect:

  • tField.setText(tField.getText() + " is the text that was in the field.");

  • This will combine the text in the field already with "is the text that was in the field."

Related Searches:

References

Resources

Comments

You May Also Like

Related Ads

Featured