Add to Google Reader or Homepage

JTextArea - An Example

JTextArea


Before discussing TextArea let us know the difference between TextField and TextArea,
The difference between these two components,are as follows.

 "A TextField is an input box where we can only enter single line of text whereas a TextArea allows you to enter multiple line of texts".

 " If the text is more than the display area of the Field a TextField will never grow but the TextArea will grow".

Creating a TextArea


A TextArea can be created by using the  JTextArea class of the Swing package as follows,

JTextArea area=new JTextArea(height,width);

Here 'height' and 'width' specifies the number of rows and columns  of text that should be  supported respectively.

Following program explains you how to create and add TextArea into a container,

TextAreaDemo.java

import javax.swing.*;
import java.awt.*;
class TextAreaDemo extends JFrame
{
public TextAreaDemo()
{
setTitle("TextAreaDemo");
setSize(400,400);
setLocationByPlatform(true);
JPanel p=new JPanel();
JLabel lb=new JLabel("TextArea");
p.add(lb);
JPanel p1=new JPanel();
JTextArea area=new JTextArea(10,25);//Text Area of height 10 rows and width 25 Columns 
area.setLineWrap(true);
p1.add(area);
add(p,BorderLayout.NORTH);
add(p1,BorderLayout.CENTER);
}
} 
 
 

TextAreaMain.java


import javax.swing.*;
import java.util.*;
class TextAreaMain
{
public static void main(String args[])
{
TextAreaDemo Areademo=new TextAreaDemo();
Areademo.setVisible(true);
Areademo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}


OUTPUT:



 



 As you see the above program it is very simple to create and add a textarea into a panel,but there are some important things that should be noted here, they are,

1. If you see this line  area.setLineWrap(true);  you can identify that Line Wrap is not supported in TextArea by default. So you have to invoke this method explicitly to include this feature into TextArea.

2. As i have said before, if the text to be displayed is more than the display size then the TextArea will grow until it reaches the window size and after that text would be clipped.

3. Like TextField, it also supports setText() and getText() methods to set and retrieve the text to/from the TextArea...



 

 
 
java errors and exceptions © 2010 | Designed by Chica Blogger | Back to top