Button, Label, TextField, and TextArea controls

 

The Button class 

Object

\

Component

 

\

Button

  1. Implementing the ActionListener interface

  2. Registering an ActionListener by calling the button's addActionListener() method

  3. Coding an actionPerformed() method within the registered ActionListener that defines the processing to be performed 

When the user clicks the button, an ActionEvent will automatically be sent to the actionPerformed() method of the registered ActionListener for processing.

Button yesButton = new Button("YES"); 

will create a button having the label "YES". The preferred size of the button is determined by the size of its label at instantiation (depending upon the layout manager).

Method

Usage

addActionListener()

Adds the specified ActionListener to receive ActionEvent objects from this button

getActionCommand()

Returns the command name of the action event fired by this button

getLabel()

Gets the label of this button

removeActionListener()

Removes the specified action listener so it no longer receives ActionEvent objects from this button

setActionCommand()

Sets the command name for the ActionEvent objects fired by this button

setLabel()

Sets the label of this button

Consult the help facility of your Java development environment or the Java API for more details.

Example:

import java.awt.*;
import java.awt.event.*;

public class App extends Frame implements WindowListener, ActionListener {

  Button stop;
  Button go;

  public static void main(String[] args) {
    App myWindow = new App("Stop and go");
    myWindow.setSize(250,150);
    myWindow.setVisible(true);
  }

  public App(String title) {
    super(title);
    setLayout(new GridLayout(1,2));
    setFont(new Font("Serif", Font.BOLD, 20));
    setBackground(Color.lightGray);
    setForeground(Color.white);
    addWindowListener(this);
    stop = new Button("Stopped");
    stop.setActionCommand("STOP");
    stop.setEnabled(false);
    stop.addActionListener(this);
    add(stop);
    go = new Button("GO");
    go.setActionCommand("GO");
    go.setBackground(Color.green);
    go.setEnabled(true);
    go.addActionListener(this);
    add(go);
  }

  public void actionPerformed(ActionEvent e) {
    if (((Button)e.getSource()).getActionCommand().equals("GO")) {
      go.setLabel("Going");
      go.setBackground(this.getBackground());
      go.setEnabled(false);
      stop.setLabel("STOP");
      stop.setBackground(Color.red);
      stop.setEnabled(true);
    }
    if (((Button)e.getSource()).getActionCommand().equals("STOP")) {
      stop.setLabel("Stopped");
      stop.setBackground(this.getBackground());
      stop.setEnabled(false);
      go.setLabel("GO");
      go.setBackground(Color.green);
      go.setEnabled(true);
    }
  }

  public void windowClosing(WindowEvent e) {
    dispose();
    System.exit(0);
  }

  public void windowOpened(WindowEvent e) {}
  public void windowActivated(WindowEvent e) {}
  public void windowIconified(WindowEvent e) {}
  public void windowDeiconified(WindowEvent e) {}
  public void windowDeactivated(WindowEvent e) {}
  public void windowClosed(WindowEvent e) {}
}

Notes:

  1. The Button references stop and go are instance variables of the class

  2. The main() method sets the frame's size and makes it visible

  3. The first part of the class constructor passes the frame's title through to the superclass constructor, specifies the frame's layout manager, font, and color scheme, and registers a WindowListener for WindowEvents. It then instantiates the two buttons, registers their ActionListener and adds them to the frame. Note that the stop button is initially disabled and has an action command of "STOP" while the go button is initially enabled, has a green background, and has an action command of "GO".

  4. The actionPerformed() method is automatically called when the user clicks an enabled button and receives an ActionEvent object as a parameter. To determine which button was clicked, the getSource() method of the ActionEvent object is cast as a Button object and its action command compared to the action command that was set for each button. Alternatively, the objects could have been compared as shown by the following test for a go button event:

if (e.getSource().equals(go)) {

The logic of this sample changes each button's label and background color and flips which button is currently enabled.

 

The Label class 

Object

\

Component

 

\

Label

Label someLabel = new Label("Hello World!"); 

will create a label having the value "Hello World!". The text will be left-aligned within the label area and the preferred size of the label is determined by the size of the string used to instantiate it (depending upon the layout manager).

Field

Usage

CENTER

Indicates that text should be centered within the label area

LEFT

Indicates that text should be left-aligned within the label area

RIGHT

Indicates that text should be right-aligned within the label area

Method

Usage

getAlignment()

Gets the current alignment of this label

getText()

Gets the text of this label

setAlignment()

Sets the alignment of this label

setText()

Sets the text for this label

Consult the help facility of your Java development environment or the Java API for more details.

Example:

import java.awt.*;
import java.awt.event.*;

public class App extends Frame implements WindowListener {

  Label theLabel;
  Panel buttonPanel;
  Button left, right, center;

  public static void main(String[] args) {
    App myWindow = new App("Align the Label");
    myWindow.setSize(350,150);
    myWindow.setVisible(true);
  }

  public App(String title) {
    super(title);
    addWindowListener(this);
    theLabel = new Label("I'm left-aligned by default");
    theLabel.setForeground(Color.red);
    theLabel.setFont(new Font("Serif", Font.BOLD, 16));
    add(theLabel);
    buttonPanel = new Panel();
    buttonPanel.setLayout(new GridLayout(1,3));
    left = new Button("Left-align");
    left.addActionListener(
      new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          theLabel.setText("Now I'm left-aligned");
          theLabel.setAlignment(Label.LEFT);
        }
      }
    );
    buttonPanel.add(left);
    center = new Button("Center");
    center.addActionListener(
      new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          theLabel.setText("Now I'm centered");
          theLabel.setAlignment(Label.CENTER);
        }
      }
    );
    buttonPanel.add(center);
    right = new Button("Right-align");
    right.addActionListener(
      new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          theLabel.setText("Now I'm right-aligned");
          theLabel.setAlignment(Label.RIGHT);
        }
      }
    );
    buttonPanel.add(right);
    add(buttonPanel, BorderLayout.SOUTH);
  }

  public void windowClosing(WindowEvent e) {
    dispose();
    System.exit(0);
  }

  public void windowOpened(WindowEvent e) {}
  public void windowActivated(WindowEvent e) {}
  public void windowIconified(WindowEvent e) {}
  public void windowDeiconified(WindowEvent e) {}
  public void windowDeactivated(WindowEvent e) {}
  public void windowClosed(WindowEvent e) {}
}

Notes:

  1. The class has instance variables to reference the label (theLabel) and a panel (buttonPanel) which will contain three buttons (left, right, and center)

  2. The main() method sets the frame's size and makes it visible

  3. After some initial overhead, the class constructor instantiates thelabel and adds it to the application frame. It then instantiates the buttonPanel with a GridLayout. The left, right, and center buttons are then created with each having an inner ActionListener to modify and re-align the label's text when the button is clicked. The buttons are added to the buttonPanel and the buttonPanel is added to the application frame.

 

The TextField class 

Object

\

Component

   

\

TextComponent

\

TextField

TextField acctNo = new TextField(10); 

will create an empty text field large enough to display 10 characters of average width without scrolling. Other constructors allow for an initial message to be displayed. Refer to Java API documentation for details.

Method

Usage

addActionListener()

Adds the specified ActionListener to receive ActionEvent objects from this text field

getColumns()

Gets the number of columns in this text field

removeActionListener()

Removes the specified action listener so it no longer receives ActionEvent objects from this text field

setColumns()

Sets the number of columns in this text field

Method

Usage

getSelectedText()

Gets the user selected text from the text within this text component

getText()

Gets all text within this text component

isEditable()

Indicates whether or not the text component may be modified by the user

setEditable()

Sets the flag that determines whether or not this text component may be modified by the user

setText()

Sets the text for this text component

Consult the help facility of your Java development environment or the Java API for more details.

Example:

import java.awt.*;
import java.awt.event.*;

public class App extends Frame implements WindowListener {

  TextField radiusField;
  TextField resultField;

  public static void main(String[] args) {
    App myWindow = new App("Area calculator");
    myWindow.setSize(300,100);
    myWindow.setVisible(true);
  }

  public App(String title) {
    super(title);
    addWindowListener(this);
    setBackground(Color.lightGray);
    setLayout(new FlowLayout());
    add(new Label("Radius of circle:"));
    radiusField = new TextField(5);
    radiusField.addActionListener(
      new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          if (radiusField.getText().length() == 0) {
            resultField.setText("You must enter a radius");
          }
          else {
            double radius =

              Double.parseDouble(radiusField.getText().trim());
            if (radius <= 0) {
              resultField.setText("Invalid radius specified");
            }
            else {
              double area = Math.PI * radius * radius;
              resultField.setText("Resulting area: " + area);
            }
          }
        }
      }
    );
    add(radiusField);
    resultField = new TextField("", 30);
    resultField.setEditable(false);
    add(resultField);
  }

  public void windowClosing(WindowEvent e) {
    dispose();
    System.exit(0);
  }

  public void windowOpened(WindowEvent e) {}
  public void windowActivated(WindowEvent e) {}
  public void windowIconified(WindowEvent e) {}
  public void windowDeiconified(WindowEvent e) {}
  public void windowDeactivated(WindowEvent e) {}
  public void windowClosed(WindowEvent e) {}
}

Notes:

  1. The class has instance variables to reference two text fields (radiusField and resultField)

  2. Both the text fields are instantiated and added to the application frame in the class constructor. The radiusField is created with a width of 5 columns and its action listener is registered and defined using an inner ActionListener. If the user fails to enter a radius or if the radius is less than or equal to zero, an appropriate message is displayed in the resultField. Otherwise, the area of the circle is calculated and displayed in the resultField. The resultField is created with no initial string and a width of 30 columns. Because it will be used for output only, it is set to be non-editable.

  3. A runtime exception will occur if the user enters an invalid numeric value for the radius. Catching and processing exceptions will be covered later. 

 

The TextArea class 

Object

\

Component

   

\

TextComponent

\

TextArea

TextArea productDescription = new TextArea(5,20); 

will create an empty text area that will display 5 rows with 20 characters of average width in each row. Both horizontal and vertical scrolling will be automatically provided. Other constructors allow for an initial message to be displayed and permit customized scrolling. Refer to Java API documentation for details.

Field

Usage

SCROLLBARS_BOTH

Create and display both vertical and horizontal scrollbars

SCROLLBARS_HORIZONTAL_ONLY

Create and display horizontal scrollbar only

SCROLLBARS_NONE

Do not create or display any scrollbars

SCROLLBARS_VERTICAL_ONLY

Create and display vertical scrollbar only

Method

Usage

append()

Appends a string to the end of the text area's current text

getColumns()

Gets the number of columns in this text area

getRows()

Gets the number of rows in this text area

insert()

Inserts a string at a specified position within the text area's current text

replaceRange()

Replaces a string at a specified position within the text area's current text

setColumns()

Sets the number of columns in this text area

setRows()

Sets the number of rows in this text area

Method

Usage

addTextListener()

Adds the specified TextListener to receive TextEvent objects from this text component

getCaretPosition()

Gets the position of the insert point within this text component

getSelectedText()

Gets the user selected text from the text within this text component

getText()

Gets all text within this text component

isEditable()

Indicates whether or not the text component may be modified by the user

removeTextListener()

Removes the specified TextListener to receive TextEvent objects from this text component

setCaretPosition()

Sets the position of the insert point within this text component

setEditable()

Sets the flag that determines whether or not this text component may be modified by the user

setText()

Sets the text for this text component

Consult the help facility of your Java development environment or the Java API for more details.

Example:

import java.awt.*;
import java.awt.event.*;

public class App extends Frame implements WindowListener {

  TextArea text;
  String saveText;
  int saveCursor;
  Panel buttonPanel;
  Button submit, clear, restore;

  public static void main(String[] args) {
    App myWindow = new App("Enter comments below");
    myWindow.setSize(400,200);
    myWindow.setVisible(true);
  }

  public App(String title) {
    super(title);
    addWindowListener(this);
    text = new TextArea("",10,30,TextArea.SCROLLBARS_VERTICAL_ONLY);
    text.addTextListener(
      new TextListener() {
        public void textValueChanged(TextEvent e) {
          restore.setEnabled(false);
          saveText = text.getText();
          saveCursor = text.getCaretPosition();
        }
      }
    );
    add(text);
    buttonPanel = new Panel();
    buttonPanel.setLayout(new GridLayout(1,3));
    submit = new Button("Submit");
    submit.addActionListener(
      new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          text.setText("Your comments have been recorded");
          restore.setEnabled(true);
        }
      }
    );
    buttonPanel.add(submit);
    clear = new Button("Clear");
    clear.addActionListener(
      new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          text.setText("");
          restore.setEnabled(true);
          text.requestFocus();
        }
      }
    );
    buttonPanel.add(clear);
    restore = new Button("Restore");
    restore.setEnabled(false);
    restore.addActionListener(
      new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          text.setText(saveText);
          text.setCaretPosition(saveCursor);
          restore.setEnabled(false);
          text.requestFocus();
        }
      }
    );
    buttonPanel.add(restore);
    add(buttonPanel, BorderLayout.SOUTH);
  }

  public void windowClosing(WindowEvent e) {
    dispose();
    System.exit(0);
  }

  public void windowOpened(WindowEvent e) {}
  public void windowActivated(WindowEvent e) {}
  public void windowIconified(WindowEvent e) {}
  public void windowDeiconified(WindowEvent e) {}
  public void windowDeactivated(WindowEvent e) {}
  public void windowClosed(WindowEvent e) {}
}

Notes:

  1. The class has several instance variables. text will reference the text area used to edit and display multiple lines of text. saveText and saveCursor will be used to restore the previous contents of the text area and reposition the insert point following a submit or a clear operation. buttonPanel will reference a panel of three buttons (submit, clear, and restore) that will trigger various processing actions.

  2. The text area (text) is instantiated in the class constructor to display an empty string in an area 10 rows high and 30 columns wide with a vertical scrollbar. Its TextListener is then registered and implemented as an inner interface. Whenever the user makes a change to the contents of the text area, the restore button will be disabled and the contents of the text area and the insert point location will be saved. After instantiation, the text area is added to the center of the application frame (which overrides its preferred row and column size).

  3. The button panel is instantiated along with each of its three buttons in the class constructor. The submit button has a registered inner ActionListener to replace the contents of the text area with a message and enable the restore button.  The clear button has a registered inner ActionListener to replace the contents of the text area with an empty string, enable the restore button, and request focus for the text area to make it the active component (so the user doesn't have to click on the text area to get an insert point).  The restore button has a registered inner ActionListener to restore the previously saved text area contents and cursor position, disable the restore button, and request focus for the text area. The button panel is added to the SOUTH in the frame's BorderLayout.

  4. When running this sample, be sure to use the cut, copy, paste, undo, and other inherited features within the text area.

 

Lab exercise for Ferris students

E-mail your answers to this assignment no later than the due date listed in the class schedule.

 

Review questions

  1. You want to construct a text field that can display 15 characters of average width without scrolling and can not be modified by the user. What code do you use?  (choose two)

  1. TextField myField = new TextField("", 15);
    myField.setEditable(false);

  1. TextField myField = new TextField(15);
    myField.setEditable(false);

  2. TextField myField = new TextField("", 15, false);

  3. TextField myField = new TextField(15, "");
    myField.setEditable(false);

  4. TextField myField = new TextField();
    myField.setEditable(false);

  1. Assuming that all unseen code is correct, what will result from attempting to compile and execute the following statements?

    Label yNot = new Label("Why not?");
    yNot.setEditable(false);

  1. the statement that attempts to construct the label will not compile

  1. the statement that attempts to set the label as being non-editable will not compile 

  2. the statements will compile but a runtime error will occur

  3. the label will contain the text "Why not?" and may not be modified by the user

  4. the label will contain the text "Why not?" and may still be modified by the user

  1. Assuming that all unseen code is correct and a variable width font is used (where 'i' is the narrowest character and 'W' is the widest, what will result from attempting to compile and execute the following statements?

    TextField someField = new TextField("iii");
    someField.setText("WWW");

  1. the statement that attempts to construct the text field will not compile

  1. the statement that attempts to set "WWW" in the text field will not compile

  2. the statements will compile but a runtime error will occur

  3. the text field will be widened to display "WWW" without scrolling

  4. the text field is not widened and the user must scroll to see the entire "WWW" string

  1. Which events can be fired by a TextArea object?  (choose two)

  1. ActionEvent

  2. KeyEvent

  3. TextEvent