Text areas
A JTextArea is like a JTextField except that it can have multiple lines and has more functionality. A particularly useful method is append( ); with this you can easily pour output into the JTextArea, thus making a Swing program an improvement (since you can scroll backward) over what has been accomplished thus far using command-line programs that print to standard output. As an example, the following program fills a JTextArea with the output from the geography generator in Chapter 11:
//: c14:TextArea.java
// Using the JTextArea control.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import com.bruceeckel.swing.*;
import com.bruceeckel.util.*;
public class TextArea extends JFrame {
private JButton
b = new JButton("Add Data"),
c = new JButton("Clear Data");
private JTextArea t = new JTextArea(20, 40);
private Map m = new HashMap();
public TextArea() {
// Use up all the data:
Collections2.fill(m, Collections2.geography,
CountryCapitals.pairs.length);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Iterator it = m.entrySet().iterator();
while(it.hasNext()) {
Map.Entry me = (Map.Entry)(it.next());
t.append(me.getKey() + ": "+ me.getValue()+"\n");
}
}
});
c.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
t.setText("");
}
});
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
cp.add(new JScrollPane(t));
cp.add(b);
cp.add(c);
}
public static void main(String[] args) {
Console.run(new TextArea(), 475, 425);
}
} ///:~
This is a JFrame rather than a JApplet because it reads from the local disk, and therefore cannot be run as an applet in an HTML page.
In init( ), the Map is filled with all the countries and their capitals. Note that for both buttons, the ActionListener is created and added without defining an intermediate variable, since you never need to refer to that listener again during the program. The “Add Data” button formats and appends all the data, and the “Clear Data” button uses setText( ) to remove all the text from the JTextArea.
As the JTextArea is added to the applet, it is wrapped in a JScrollPane to control scrolling when too much text is placed on the screen. That’s all you must do in order to produce full scrolling capabilities. Having tried to figure out how to do the equivalent in some other GUI programming environments, I am very impressed with the simplicity and good design of components like JScrollPane.