Java JTextArea Example
JTextArea is a swing component that displays multiple lines text.JTextField is same as JTextArea only that it displays single line text.
How to Declare JTextArea class
[public class JTextArea extends JTextComponent]
JTextArea used constructors.
- JTextArea()-create a empty JTextArea with no text.
- JTextArea(String s)-creates a JTextArea with a text inside it.
- JTextArea(int row,int col)-creates a JTextArea with specified number of rows and columns.
- JTextArea(String s,int row,int col)-creates a JTextArea with a initial text and specified number of columns and rows.
JTextArea common methods.
- void setRows(int rows)-used to set number of rows in a JTextArea.
- void setColumns(int col)-used to set number of columns.
- void setFont(Font f)-used to set Font size.
- void insert(String s,int position)-inserts a text in a specified position.
- void append(String s)-used to append text at the end.
Java JTextArea Example
[
import javax.swing.JTextArea; import javax.swing.JFrame; public class TextArea extends JFrame{ public TextArea() { super("JTextArea Example"); JTextArea area=new JTextArea(); area.setBounds(30, 30, 200, 200); add(area); setSize(300,300); setLayout(null); setVisible(true); } public static void main(String args[]) { new TextArea(); } }
]
[
import javax.swing.JButton; import javax.swing.JTextArea; import javax.swing.JLabel; import javax.swing.JFrame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class JTextAreaExample implements ActionListener{ JLabel label1,label2; JButton button; JTextArea area; public JTextAreaExample() { JFrame frame=new JFrame("JTextArea Example"); label1=new JLabel(); label1.setBounds(50,25,100,30); label2=new JLabel(); label2.setBounds(160,25,100,30); area=new JTextArea(); area.setBounds(20,75,250,200); button=new JButton("Count Words"); button.setBounds(100,300,120,30); button.addActionListener(this); frame.add(label1); frame.add(label2); frame.add(area); frame.add(button); frame.setSize(450,450); frame.setLayout(null); frame.setLocationRelativeTo(null); frame.setVisible(true); } public void actionPerformed(ActionEvent event) { String text=area.getText(); String words[]=text.split("\\s"); label1.setText("Words: "+words.length); label2.setText("Characters: "+text.length()); } public static void main(String args[]) { new JTextAreaExample(); } }
]