Text Areas

A text area, which is defined in the class javax.swing.JTextArea, can display multiple lines of text.  When the text extends beyond the borders of the widget, the user can view it by manipulating vertical and horizontal scroll bars.  The next screen shot shows a program that displays information about an employee in a text area. 



The code for this program is in the files TextAreaDemo.java and Employee.java. The first file defines the main window class and the main method. The second file defines an Employee class to represent employee objects. An employee object tracks an employee's name, pay rate, and the hours worked for each of five days.

At program startup, the GUI program adds a text area and two buttons to the window, in the usual manner. It then creates an instance of the Employee class with some sample data, and calls the toString method on this object to obtain the text to display in the text area. The buttons allow the user to view the employee's total hours and total pay. Here is the code for the main window class:

import javax.swing.*;

import BreezySwing.*;


public class TextAreaDemo extends GBFrame{


   JTextArea outputArea  = addTextArea ("", 1,1,2,5);

   JButton totalHoursBtn = addButton ("Total hours", 6,1,1,1);

   JButton totalPayBtn   = addButton ("Total pay",   6,2,1,1);


   private Employee emp;


   public TextAreaDemo(){

      int [] hours = {8, 10, 6, 8, 9};

      emp = new Employee ("Ken", 15.25, hours);

      outputArea.setText (emp.toString());

      outputArea.setEditable (false);



   public void buttonClicked(JButton buttonObj){

      if (buttonObj == totalHoursBtn)

          messageBox ("Total hours: " + emp.getTotalHours());


          messageBox ("Total pay: $" + emp.computePay());



   public static void main(String[] args){

      JFrame frm = new TextAreaDemo();

      frm.setSize (200, 200);

      frm.setTitle ("Employee Info");

      frm.setVisible (true);        




Note that the text area stretches across five rows and two columns, and that the program has made this area read-only.     

In addition to the getText and setText methods, the JTextArea class includes an append method, which adds text to the end of the existing text rather than replacing it. 



Back to tutorial Next topic: Dialogs and model/view/controller