While single-line input is handled by TextField, many applications need to display and/ or edit larger bocks of text. TextArea is the AWT component that supports this feature. TextArea class provides a rectangular area (in rows and columns) for user interaction.
Editing within a TextArea is basically the same as editing within a TextField. When typing in the text area, the user can perform most of the native cut, copy, and paste operations. However, the AWT doesn’t provide specific events for these.
TextArea Useful Interface
Method | Returns | Notes |
TextArea() |
| Rows and columns are approximate, some windowing systems don’t seem “perfect” |
TextArea(int rows, int cols) |
| |
TextArea(String text) |
|
|
TextArea(String text, int rows, int cols) |
|
|
appendText(String str) | Void | Take the string on the end of the area |
getColumns() | Int | How wide is the text area |
getRows() | Int | How tall the text area |
insertText(String str, int pos) | Void | Insert the string in the existing text at the index passed in; note that this doesn’t use rows and columns |
minimumSize() | Dimension |
|
minimumSize(int rows, int cols) | Dimension |
|
preferredSize() | Dimension |
|
preferredSize(int rows, int cols) | Dimension |
|
replaceText(String str, int start, int end) | Void | Same as TextField.setText() |
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <APPLET CODE ="TextareaJavaApplet.class" WIDTH=300 HEIGHT=200> </APPLET> */
public class TextareaJavaApplet extends Applet implements ActionListener
{
TextArea txt;
Button b1,b2;
String s1,s2;
Label l1,l2,l3;
TextField t1,t2,t3;
public void init()
{
txt = new TextArea(5,30);
add(txt);
s1="This is the text which is already present in textarea\nMerry"+ "Christmas to
you\nToday it may rain";
txt.append(s1);
s2="In the middle this text will be inserted";
b1=new Button("insert Text");
add(b1);
b1.addActionListener(this);
l1=new Label("Replacing a range of above text with new text.Enter starting location");
add(l1);
t1=new TextField(10);
add(t1);
l2=new Label("Ending range");
add(l2);
t2=new TextField(10);
add(t2);
l3=new Label("Replacing with");
add(l3);
t3=new TextField(10);
add(t3);
b2=new Button("Replace");
add(b2);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
int start,end;
if(e.getSource()==b1)
{
txt.insert(s2,12);
}
if(e.getSource()==b2)
{
start=Integer.parseInt(t1.getText());
end=Integer.parseInt(t2.getText());
txt.replaceRange(t3.getText(),start,end);
}
}
}