Text fields

Bruce Eckel's Thinking in Java Contents | Prev | Next

//: TextField1.java
// Using the text field control
import java.awt.*;
import java.applet.*;
public class TextField1 extends Applet {
    b1 = new Button("Get Text"),
    b2 = new Button("Set Text");
    t = new TextField("Starting text", 30);
  String s = new String();
  public void init() {
  public boolean action (Event evt, Object arg) {
    if(evt.target.equals(b1)) {
      s = t.getSelectedText();
      if(s.length() == 0) s = t.getText();
    else if(evt.target.equals(b2)) {
      t.setText("Inserted by Button 2: " + s);
    // Let the base class handle it:
      return super.action(evt, arg);
    return true; // We've handled it here
} ///:~ 

There are several ways to construct a TextField; the one shown here provides an initial string and sets the size of the field in characters.

Pressing button 1 either gets the text you’ve selected with the mouse or it gets all the text in the field and places the result in String s . It also allows the field to be edited. Pressing button 2 puts a message and s into the text field and prevents the field from being edited (although you can still select the text). The editability of the text is controlled by passing setEditable( ) a true or false.


  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Lenovo recommends Windows 8 Pro. "I dropped my laptop getting out of the taxi." This probably sounds familiar to most IT professionals. If your employees are traveling, you know their devices are in for a rough go. Whether it's a trip to the conference room or a convention out of town, any time equipment leaves a user's desk it is at risk of being put into harm's way. Stay connected at all times, whether at the office or on the go, with agile, durable, and flexible devices like the Lenovo® …

  • As the mobile enterprise marketplace expands and customer needs grow more diverse, Samsung recognizes that solution partners and developers play an essential role by continually innovating to meet their customers' needs. Samsung works to provide these developers and partners with the latest tools and resources needed to create these solutions. Read this program guide to learn how the Samsung Enterprise Alliance Program provides partners and developers with Samsung enterprise software development kits (SDKs) …

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date