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

  • Moving from an on-premises environment to Office 365 does not remove the need to plan for disruptions or reduce the business risk requirements for protecting email services. If anything, some risks increase with a move to the cloud. Read how to ease the transition every business faces if considering or already migrating to cloud email. This white paper discusses: Setting expectations when migrating to Office 365 Understanding the implications of relying solely on Exchange Online security Necessary archiving …

  • Anthony Christie, the Chief Marketing Officer for Level Communications, is responsible for customer experience, worldwide marketing and product management. In this informative asset, he shares his insights into why a private network connection to cloud-bases applications is the right decision for your enterprise. Download now to find out more.

Most Popular Programming Stories

More for Developers

RSS Feeds

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