In this tutorial

You will learn how to...
  • How to create a JTextArea.
  • How to manipulate text in the area.

JTextArea - Part 1

The JTextArea is simply a large JTextField that can display or take in more than one line of text at a time.

It is instantiated like many of the widgets we have looked at before, so for this example we've used all the widgets we have learned about in the last three tutorials... JCheckBox, JComboBox and JRadioButton.

A small story is displayed on the JTextArea, and you can edit it by using the widgets to the right of the TextArea.
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.Color;
import java.awt.event.*;

// Class implements three different types of listener.
public class TextAreaExample implements  ActionListener, ItemListener{

    JTextArea storyArea;
    JRadioButton boyButton, girlButton;
    JComboBox nameBox;
    JCheckBox cb[] = new JCheckBox[7];

    String objects[] = {"Car", "Bike", "Dragon", "Bus", "Mouse", "Cheese",
                        "Unicycle", "Sinclair C5", "Pony"};

    String places[] = {"Office", "Hospital", "University", "Pool", "Farm",
                       "Castle", "Sewer"};

    public JPanel createContentPane (){

        JPanel totalGUI = new JPanel();

        // The main story for the JTextArea
        String story = "When I was a small boy, I always dreamed of having a Red Car.\n"+ 
                       "I'd travel in it everywhere and go and visit my mum.\n"+
                       "Sometimes I'd go and visit the Office.\n"+
                       "I loved my Red Car and it loved me.\n"; 

        // Plus we instantiate the TextArea.
        storyArea = new JTextArea(story, 5, 30);
        storyArea.setEditable(false);
        storyArea.setLineWrap(true);
        storyArea.setWrapStyleWord(true);

        // To determine the sex of the user.
        boyButton = new JRadioButton("Boy");
        boyButton.addActionListener(this);
        boyButton.setSelected(true);
        boyButton.setHorizontalAlignment(0);
        girlButton = new JRadioButton("Girl");
        girlButton.addActionListener(this);
        boyButton.setHorizontalAlignment(0);

        ButtonGroup sexGroup = new ButtonGroup();
        sexGroup.add(boyButton);
        sexGroup.add(girlButton);

        JPanel sexPanel = new JPanel();
        sexPanel.setLayout(new BoxLayout(sexPanel, BoxLayout.PAGE_AXIS));
        sexPanel.add(boyButton);
        sexPanel.add(girlButton);
        sexPanel.add(Box.createRigidArea(new Dimension(0,30)));

        // To determine the vehicle.
        nameBox = new JComboBox(objects);
        nameBox.setSelectedIndex(0);
        nameBox.addActionListener(this);
        sexPanel.add(nameBox);

        // To determine the places they have been to.
        JPanel cbPanel = new JPanel();
        cbPanel.setLayout(new BoxLayout(cbPanel, BoxLayout.PAGE_AXIS));

        cbPanel.add(Box.createRigidArea(new Dimension(10,0)));
        for(int i = 0; i < 7; i++)
        {
            cb[i] = new JCheckBox(places[i]);
            cb[i].addItemListener(this);
            cbPanel.add(cb[i]);
            cbPanel.add(Box.createHorizontalGlue());
        }
        cb[0].setSelected(true);
        cbPanel.add(Box.createRigidArea(new Dimension(10,0)));

        // This final bit of code uses a BoxLayout to space out the widgets
        // in the GUI.

        JPanel bottomPanel = new JPanel();
        bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.LINE_AXIS));

        bottomPanel.add(Box.createRigidArea(new Dimension(10,0)));
        bottomPanel.add(storyArea);
        bottomPanel.add(Box.createRigidArea(new Dimension(20,0)));
        bottomPanel.add(sexPanel);
        bottomPanel.add(Box.createRigidArea(new Dimension(20,0)));
        bottomPanel.add(cbPanel);
        bottomPanel.add(Box.createRigidArea(new Dimension(10,0)));

        totalGUI.add(bottomPanel);
        totalGUI.setOpaque(true);
        return totalGUI;
    }

    // For the List Events.
    public void valueChanged(ListSelectionEvent e) 
    {
        sortTextPanel();
    }
    // For the Action Events.
    public void actionPerformed(ActionEvent e) 
    {
        sortTextPanel();
    }
    // For the Item Events.
    public void itemStateChanged(ItemEvent e)
    {
        sortTextPanel();
    }

    // This rewrites the story depending on the actions so far in the various
    // widgets then re-sends the story to the TextArea.
    public void sortTextPanel()
    {
        String story = "When I was a small";

        if(boyButton.isSelected())
        {
            story = story + " boy, I always dreamed of having a";
        }
        else
        {
            story = story + " girl, I always dreamed of having a";
        }
        
        story = story + " "+ objects[nameBox.getSelectedIndex()] + " ";
        story = story + ".\nI'd travel in it everywhere and go and visit my mum.\n";
        story = story + "Sometimes I'd go and visit the ";

        for(int i = 0; i < 7; i++)
        {
            if(cb[i].isSelected())
            story = story + places[i] + " ";
        }
        story = story + "\nI loved my "+ objects[nameBox.getSelectedIndex()] + 
                " and it loved me.\n";

        storyArea.setText(story);
    }

    private static void createAndShowGUI() {

        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("[=] JTextArea [=]");

        TextAreaExample demo = new TextAreaExample();
        frame.setContentPane(demo.createContentPane());
        
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}
When run, this GUI looks like this. Have a go at using it.

Text Area Example

So, this program is a little more complicated as it has to use more than one event listeners, but there isn't a huge problem. All we do is list them at the class declaration.
8
public class TextAreaExample implements  ActionListener, ItemListener{
The really easy bit is instantiating the JTextArea!
There are three different variables.
The first is a String. This defines what is displayed when the GUI is invoked (started). The other two are integers and are used by the LayoutManager to define how large to make the widget. The second argument shows how many rows of text we will want to display at once, and the third argument shows how many characters along the row.

Then, we set it so the story cannot be edited. TextAreas can be used to display a large amount of text, or get the user to type it in.
32
33
        storyArea = new JTextArea(story, 5, 30);
        storyArea.setEditable(false);
We set the text area to wrap the words, so that the text will start a new line instead of making the TextArea bigger, or just not showing it at all. Linewrap wraps the lines of text, but setting wordwrap to true means only whole words will be wrapped i.e. Words are not split in the middle when they hit the end of the TextArea.
34
35
        storyArea.setLineWrap(true);
        storyArea.setWrapStyleWord(true);
Most of the code in this example has already been covered before in previous tutorials. The last thing to look at is again the Event Listeners.
97
98
99
100
101
102
103
104
105
106
107
108
109
110
    public void valueChanged(ListSelectionEvent e) 
    {
        sortTextPanel();
    }
    // For the Action Events.
    public void actionPerformed(ActionEvent e) 
    {
        sortTextPanel();
    }
    // For the Item Events.
    public void itemStateChanged(ItemEvent e)
    {
        sortTextPanel();
    }
If an event occurs, any event, the method sortTextArea() is called and the JTextArea is updated.
In sortTextArea(), the story string is edited depending what is selected in the widgets, and the JTextArea is updated by using the setText() command.
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
    public void sortTextPanel()
    {
        String story = "When I was a small";

        if(boyButton.isSelected())
        {
            story = story + " boy, I always dreamed of having a";
        }
        else
        {
            story = story + " girl, I always dreamed of having a";
        }
        
        story = story + " "+ objects[nameBox.getSelectedIndex()] + " ";
        story = story + ".\nI'd travel in it everywhere and go and visit my mum.\n";
        story = story + "Sometimes I'd go and visit the ";

        for(int i = 0; i < 7; i++)
        {
            if(cb[i].isSelected())
            story = story + places[i] + " ";
        }
        story = story + "\nI loved my "+ objects[nameBox.getSelectedIndex()] + 
                " and it loved me.\n";

        storyArea.setText(story);
    }
Questions

Questions on the Area of Text.

Question 1. How do we make lines of text in a JTextArea automatically start a new line when the end of the widget is reached?

  • a) .setLineWrap(true);
  • b) .setWordWrap(true);
  • c) .setNewLine(true);

Question 2. How do we make sure words are kept together when a new line is created?

  • a) .setLineWrap(true);
  • b) .setWordWrap(true);
  • c) .setNewLine(true);

Question 3. How do we stop people from changing the text inside?

  • a) .setForeground(false);
  • b) .setEditable(false);
  • c) .setChangeable(false);

Question 4. How do we set the text inside the JTextArea?

  • a) .setText(String);
  • b) .setWords(String);
  • c) .setString(String);




Back Top Next
Email Me
Code Style


Required Lessons

External Links

Created and Edited by Stuart Davidson
All Rights Reserved ©

Valid XHTML 1.0 Strict