JTextArea Example
This JTextArea example allows the user to enter text on more than one line. A JTextArea has various constructors. This one has a string as the first parameter followed by the number of rows and columns of the area.
A button has been added to the interface to enable the program to retrieve the text.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// JTextArea Example
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class JTextAreaExample {
public static void main(String[] args) {
JFrame frame = new JFrame();
Container cp = frame.getContentPane();
cp.setLayout(new FlowLayout());
JLabel lab = new JLabel("Enter your message below");
cp.add(lab);
final JTextArea jta = new JTextArea("Type here",10,20);
cp.add(jta);
JButton b = new JButton("Submit");
cp.add(b);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s = jta.getText();
System.out.println("mesage="+s);
}
});
frame.setSize(300,250);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
17-18 The textarea is added to the interface. Notice the use of the keyword final. A final variable, once initialized, cannot be assigned to later in the execution. Its value is therefore frozen. It is this fact that enables the textarea instance to be used in the code of the ActionListener, which will be executed at some unknown future time when the button is activated.
23-28 The action listener is added to the button.
When the button is pressed the text in the textarea will be retrieved using the method getText() and output.
A more normal scenario would have the text being sent to a web site for processing.
