Case Study 7
Case Study 7
To demonstrate the JTextArea component, fonts, menus, and file choosers, we present a simple
text editor application. This application allows you to create new text files and open existing
text files. The file contents are displayed in a text area. You can also change the font and style
of the text that is displayed in the text area. The application’s window is shown in Figure CS7-1.
Line wrapping is turned on, using word wrap style, and the text area is in a scroll pane.
From Starting Out with Java: From Control Structures through Objects, Sixth Edition. Tony Gaddis.
Copyright © 2016 by Pearson Education, Inc. All rights reserved.
CS7-1
CS7-2 Case Study 7 A Simple Text Editor Application
The application uses a menu system to perform these operations, which is shown in
Figure CS7-2.
Each menu item generates an action event that is handled by an action listener. The follow-
ing section presents a summary of the actions performed by each menu item.
File Menu
New This menu item clears any text that is stored in the text area. In addition, the
class’s filename field is set to null. The filename field contains the path and
name of the file that is currently displayed in the text area.
Open This menu item displays a file chooser that allows the user to select a file to
open. If the user selects a file, it is opened and its contents are read into the text
area. The path and name of the file are stored in the filename field.
Save This menu item saves the contents of the text area. The contents are saved to the
file with the name and path stored in the filename field. If the filename field is
set to null, which would indicate that the file has not been saved yet, then this
menu item performs the same action as the Save As menu item.
Save As This menu item displays a file chooser that allows the user to select a location
and file name. The contents of the text area are written to the selected file, and
the path and file name are stored in the filename field. (Be careful when using
this menu item. As it is currently written, this application does not warn you
when you are about to overwrite an existing file!)
Exit This menu item ends the application.
Font Menu
Monospaced This radio button menu item changes the text area’s font to Monospaced.
Serif This radio button menu item changes the text area’s font to Serif.
SansSerif This radio button menu item changes the text area’s font to SansSerif.
Italic This check box menu item changes the text area’s style to italic.
Bold This check box menu item changes the text area’s style to bold.
Code Listing CS7-1 shows the code for the TextEditor class. The main method creates
an instance of the class, which displays the text editor window. Figure CS7-3 shows the
window displaying text in various fonts and styles.
Case Study 7 A Simple Text Editor Application CS7-3
1 import java.awt.*;
2 import java.awt.event.*;
3 import javax.swing.*;
4 import java.io.*;
5 import java.util.Scanner;
6
7 /**
8 The TextEditor class is a simple text editor.
9 */
10
11 public class TextEditor extends JFrame
12 {
13 // The following are fields for the menu system.
14 // First, the menu bar
15 private JMenuBar menuBar;
16
CS7-4 Case Study 7 A Simple Text Editor Application
17 // The menus
18 private JMenu fileMenu;
19 private JMenu fontMenu;
20
21 // The menu items
22 private JMenuItem newItem;
23 private JMenuItem openItem;
24 private JMenuItem saveItem;
25 private JMenuItem saveAsItem;
26 private JMenuItem exitItem;
27
28 // The radio button menu items
29 private JRadioButtonMenuItem monoItem;
30 private JRadioButtonMenuItem serifItem;
31 private JRadioButtonMenuItem sansSerifItem;
32
33 // The checkbox menu items
34 private JCheckBoxMenuItem italicItem;
35 private JCheckBoxMenuItem boldItem;
36
37 private String filename; // To hold the file name
38 private JTextArea editorText;// To display the text
39 private final int NUM_LINES = 20; // Lines to display
40 private final int NUM_CHARS = 40; // Chars per line
41
42 /**
43 Constructor
44 */
45
46 public TextEditor()
47 {
48 // Set the title.
49 setTitle("Text Editor");
50
51 // Specify what happens when the close
52 // button is clicked.
53 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
54
55 // Create the text area.
56 editorText = new JTextArea(NUM_LINES, NUM_CHARS);
57
58 // Turn line wrapping on.
59 editorText.setLineWrap(true);
60 editorText.setWrapStyleWord(true);
61
62 // Create a scroll pane and add the text area to it.
63 JScrollPane scrollPane = new JScrollPane(editorText);
64
Case Study 7 A Simple Text Editor Application CS7-5
113 openItem.setMnemonic(KeyEvent.VK_O);
114 openItem.addActionListener(new OpenListener());
115
116 // Create the Save menu item.
117 saveItem = new JMenuItem("Save");
118 saveItem.setMnemonic(KeyEvent.VK_S);
119 saveItem.addActionListener(new SaveListener());
120
121 // Create the Save As menu item.
122 saveAsItem = new JMenuItem("Save As");
123 saveAsItem.setMnemonic(KeyEvent.VK_A);
124 saveAsItem.addActionListener(new SaveListener());
125
126 // Create the Exit menu item.
127 exitItem = new JMenuItem("Exit");
128 exitItem.setMnemonic(KeyEvent.VK_X);
129 exitItem.addActionListener(new ExitListener());
130
131 // Create a menu for the items we just created.
132 fileMenu = new JMenu("File");
133 fileMenu.setMnemonic(KeyEvent.VK_F);
134
135 // Add the items and some separator bars to the menu.
136 fileMenu.add(newItem);
137 fileMenu.add(openItem);
138 fileMenu.addSeparator();// Separator bar
139 fileMenu.add(saveItem);
140 fileMenu.add(saveAsItem);
141 fileMenu.addSeparator();// Separator bar
142 fileMenu.add(exitItem);
143 }
144
145 /**
146 The buildFontMenu method creates the font menu
147 and populates it with its menu items.
148 */
149
150 private void buildFontMenu()
151 {
152 // Create the Monospaced menu item.
153 monoItem = new JRadioButtonMenuItem("Monospaced");
154 monoItem.addActionListener(new FontListener());
155
156 // Create the Serif menu item.
157 serifItem = new JRadioButtonMenuItem("Serif");
158 serifItem.addActionListener(new FontListener());
159
Case Study 7 A Simple Text Editor Application CS7-7
207 /**
208 Private inner class that handles the event that
209 is generated when the user selects Open from
210 the file menu.
211 */
212
213 private class OpenListener implements ActionListener
214 {
215 public void actionPerformed(ActionEvent e)
216 {
217 int chooserStatus;
218
219 JFileChooser chooser = new JFileChooser();
220 chooserStatus = chooser.showOpenDialog(null);
221 if (chooserStatus == JFileChooser.APPROVE_OPTION)
222 {
223 // Get a reference to the selected file.
224 File selectedFile = chooser.getSelectedFile();
225
226 // Get the path of the selected file.
227 filename = selectedFile.getPath();
228
229 // Open the file.
230 if (!openFile(filename))
231 {
232 JOptionPane.showMessageDialog(null,
233 "Error reading " +
234 filename, "Error",
235 JOptionPane.ERROR_MESSAGE);
236 }
237 }
238 }
239
240 /**
241 The openFile method opens the file specified by
242 filename and reads its contents into the text
243 area. The method returns true if the file was
244 opened and read successfully, or false if an
245 error occurred.
246 @param filename The name of the file to open.
247 */
248
249 private boolean openFile(String filename)
250 {
251 boolean success;
252 String inputLine, editorString = "";
253
Case Study 7 A Simple Text Editor Application CS7-9
254 try
255 {
256 // Open the file.
257 File file = new File(filename);
258 Scanner inputFile = new Scanner(file);
259
260 // Read the file contents into the editor.
261 while (inputFile.hasNext())
262 {
263 // Read a line from the file.
264 inputLine = inputFile.nextLine();
265
266 // Append it to the string to display
267 // in the editor.
268 editorString = editorString +
269 inputLine + "\n";
270 }
271
272 // Display the string that was read from the
273 // file in the editor.
274 editorText.setText(editorString);
275
276 // Close the file.
277 inputFile.close();
278
279 // Indicate that everything went OK.
280 success = true;
281 }
282 catch (IOException e)
283 {
284 // Something went wrong.
285 success = false;
286 }
287
288 // Return our status.
289 return success;
290 }
291 }
292
293 /**
294 Private inner class that handles the event that
295 is generated when the user selects Save or Save
296 As from the file menu.
297 */
298
299 private class SaveListener implements ActionListener
300 {
301 public void actionPerformed(ActionEvent e)
CS7-10 Case Study 7 A Simple Text Editor Application
302 {
303 int chooserStatus;
304
305 // If the user selected Save As, or the contents
306 // of the editor have not been saved, use a file
307 // chooser to get the file name. Otherwise, save
308 // the file under the current file name.
309
310 if (e.getActionCommand() == "Save As" ||
311 filename == null)
312 {
313 JFileChooser chooser = new JFileChooser();
314 chooserStatus = chooser.showSaveDialog(null);
315 if (chooserStatus == JFileChooser.APPROVE_OPTION)
316 {
317 // Get a reference to the selected file.
318 File selectedFile =
319 chooser.getSelectedFile();
320
321 // Get the path of the selected file.
322 filename = selectedFile.getPath();
323 }
324 }
325
326 // Save the file.
327 if (!saveFile(filename))
328 {
329 JOptionPane.showMessageDialog(null,
330 "Error saving " +
331 filename,
332 "Error",
333 JOptionPane.ERROR_MESSAGE);
334 }
335 }
336
337 /**
338 The saveFile method saves the contents of the
339 text area to a file. The method returns true if
340 the file was saved successfully, or false if an
341 error occurred.
342 @param filename The name of the file.
343 @return true if successful, false otherwise.
344 */
345
346 private boolean saveFile(String filename)
347 {
348 boolean success;
349 String editorString;
350 PrintWriter outputFile;
Case Study 7 A Simple Text Editor Application CS7-11
351
352 try
353 {
354 // Open the file.
355 outputFile = new PrintWriter(filename);
356
357 // Write the contents of the text area
358 // to the file.
359 editorString = editorText.getText();
360 outputFile.print(editorString);
361
362 // Close the file.
363 outputFile.close();
364
365 // Indicate that everything went OK.
366 success = true;
367 }
368 catch (IOException e)
369 {
370 // Something went wrong.
371 success = false;
372 }
373
374 // Return our status.
375 return success;
376 }
377 }
378
379 /**
380 Private inner class that handles the event that
381 is generated when the user selects Exit from
382 the file menu.
383 */
384
385 private class ExitListener implements ActionListener
386 {
387 public void actionPerformed(ActionEvent e)
388 {
389 System.exit(0);
390 }
391 }
392
393 /**
394 Private inner class that handles the event that
395 is generated when the user selects an item from
396 the font menu.
397 */
398
CS7-12 Case Study 7 A Simple Text Editor Application