JTextArea

 

JTextAreas make a multi-lined JLabel.

 

JTextArea Demo Picture

 

Some sample code:

import java.awt.*;  import java.awt.event.*;
   import javax.swing.*;  import java.applet.*;
public class JTextAreaDemo extends Applet implements ActionListener
{
   public void init ()
   {
   resize (300, 240);
 JTextArea words1 = new JTextArea (10, 20);
   words1.setFont (new Font ("Arial", Font.BOLD, 14));
   words1.setForeground (Color.white);
   words1.setBackground (Color.red);
   words1.setLineWrap (true);
   words1.setEditable (false);
   words1.append ("Some more code for a JTextArea");
   words1.append ("\nis found on this program!");
   words1.append ("\n\nIt shows you how to make a");
   words1.append ("\nbackground colour and also how");
   words1.append ("\nto add new lines to the space");
   words1.append ("\nwhere you are typing.");
   words1.append ("\nFinally, it shows you how to ");
   words1.append ("\nremove the scrollbars and how");
   words1.append ("\nto make it uneditable.");
   add (words1);
 }
 
 public void actionPerformed (ActionEvent e)
 {
 }
 
 protected static ImageIcon createImageIcon (String path)
 {
   java.net.URL imgURL = JTextAreaDemo.class.getResource (path);
   if (imgURL != null)
   { return new ImageIcon (imgURL);
   }
   else
   { System.err.println ("Couldn't find file: " + path);
     return null;
   }
 }
}

 

 

 

TextArea Questions

 

  1. Type in the below code.

import java.awt.*;

import java.applet.*;

import javax.swing.*;

public class testText extends Applet

{
    JTextArea TA;
    public void init ()

    {

        TA = new JTextArea ("Hello, ");

        add (TA);

    }

}

 

(A)   What appears on the screen?

(B)    How do you declare a TextArea?

(C)    What does the call to the constructor look like?

(D)    How to you add a TextArea to the screen?

  1. Add this line at the bottom of the init method.

TA.append("how are you? ");

(A)   How does this change the screen?

(B)    Write the code to add “I really want to know” to the screen.

  1. Add this line to the bottom of the init method.

TA.append("\n");

TA.append("I am fine. ");

(A)   How does this change what is on the screen?

(B)    What does ‘\n’ do?

  1. Change the constructor in the following ways. What does each one do?

(A)   TA= new JTextArea(“Hello”, 10, 20);

(B)    TA = new JTextArea(10,20);

  1. What does TA.setText(""); do?

  2. Go to the Help File and see if you can use it to figure out how to change the constructor call so that the TextArea has no scroll bars.