A Simple Text Editor Application

Similar documents
Chapter 13 Lab Advanced GUI Applications Lab Objectives. Introduction. Task #1 Creating a Menu with Submenus

Chapter 13 Lab Advanced GUI Applications

Java - Applications. The following code sets up an application with a drop down menu, as yet the menu does not do anything.

Building Graphical User Interfaces. Overview

Building Graphical User Interfaces. GUI Principles

Overview. Building Graphical User Interfaces. GUI Principles. AWT and Swing. Constructing GUIs Interface components GUI layout Event handling

Inheritance (cont) Abstract Classes

JAVA NOTES GRAPHICAL USER INTERFACES

More Swing. CS180 Recitation 12/(04,05)/08

Theory Test 3A. University of Cape Town ~ Department of Computer Science. Computer Science 1016S ~ For Official Use

Part 3: Graphical User Interface (GUI) & Java Applets

Attempt FOUR questions Marking Scheme Time: 120 mins

import javax.swing.*; import java.awt.*; import java.awt.event.*;

Chapter 12 GUI Basics

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Queens College, CUNY Department of Computer Science. CS 212 Object-Oriented Programming in Java Practice Exam 2. CS 212 Exam 2 Study Guide

Lösningsförslag till exempeldugga

II 12, JFileChooser. , 2. SolidEllipse ( 2), PolyLine.java ( 3). Draw.java

GUI Components Continued EECS 448

JAVA NOTES GRAPHICAL USER INTERFACES

Handout 14 Graphical User Interface (GUI) with Swing, Event Handling

PART 23. Java GUI Advanced JList Component. more items.

JRadioButton account_type_radio_button2 = new JRadioButton("Current"); ButtonGroup account_type_button_group = new ButtonGroup();

Example 3-1. Password Validation

Class 16: The Swing Event Model

STREAMS. (fluxos) Objetivos

A sample print out is: is is -11 key entered was: w

Based on slides by Prof. Burton Ma

Java Programming Lecture 6

JLayeredPane. Depth Constants in JLayeredPane

Adding Buttons to StyleOptions.java

11/27/2007 TOPICS CHAPTER TOPICS LISTS READ ONLY TEXT FIELDS. Advanced GUI Applications. This module discusses the following main topics:

1 (6) Lösningsförslag Objektorienterade applikationer Provdatum Program DAI 2 Läsår 2016/2017, lp 3. Uppgift 1 (1+1+1 p) a)

COURSE DESCRIPTION. John Lewis and William Loftus; Java: Software Solutions; Addison Wesley

CSIS 10A Assignment 7 SOLUTIONS

1.00 Lecture 14. Lecture Preview

Graphical User Interfaces 2

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

8/23/2014. Chapter Topics. Chapter Topics. Lists. Read Only Text Fields. Chapter 13: Advanced GUI Applications

Today. cisc3120-fall2012-parsons-lectiii.3 2

1.1 GUI. JFrame. import java.awt.*; import javax.swing.*; public class XXX extends JFrame { public XXX() { // XXX. init() main() public static

MIT AITI Swing Event Model Lecture 17

Java Help Files. by Peter Lavin. May 22, 2004

CSE143 - Project 3A Turn-in Receipt

Lesson 3: Accepting User Input and Using Different Methods for Output

Object-Oriented Programming Design. Topic : User Interface Components with Swing GUI Part III

Class 14: Introduction to the Swing Toolkit

16-Dec-10. Consider the following method:

Java Project P6 Event Handling

Project 1. Java Data types and input/output 1/17/2014. Primitive data types (2) Primitive data types in Java

Practical Scala. Dianne Marsh Emerging Technology for the Enterprise Conference 03/26/2009

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Programming graphics

Layouts and Components Exam

AP CS Unit 11: Graphics and Events

RAIK 183H Examination 2 Solution. November 10, 2014

CSE 143 Sp03 Midterm 2 Sample Solution Page 1 of 7. Question 1. (2 points) What is the difference between a stream and a file?

File Input and Output Recitation 04/03/2009. CS 180 Department of Computer Science, Purdue University

Introduction to the JAVA UI classes Advanced HCI IAT351

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling

Window Interfaces Using Swing Objects

I/O Framework and Case Study. CS151 Chris Pollett Nov. 2, 2005.

CSE 8B Intro to CS: Java

PRÁCTICO 1: MODELOS ESTÁTICOS INGENIERÍA INVERSA DIAGRAMAS DE CLASES

Input from Files. Buffered Reader


Graphical User Interfaces 2

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

11/1/2011. Chapter Goals

GPolygon GCompound HashMap

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

CN208 Introduction to Computer Programming

DM503 Programming B. Peter Schneider-Kamp.

Graphical User Interfaces 2

COSC 123 Computer Creativity. Graphics and Events. Dr. Ramon Lawrence University of British Columbia Okanagan

Variables of class Type. Week 8. Variables of class Type, Cont. A simple class:

Sorting/Searching and File I/O

Stating Your Preferences

Chapter 13 GUI Basics. Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved.

Apéndice A. Código fuente de aplicación desarrollada para probar. implementación de IPv6

Basics of programming 3. Java GUI and SWING

Lösningsförslag till tentamen

Lab 5: Java IO 12:00 PM, Feb 21, 2018

Swing Programming Example Number 2

Introduction This assignment will ask that you write a simple graphical user interface (GUI).

Implementing Graphical User Interfaces

Computer Science II - Test 1

Window Interfaces Using Swing Objects

enum: Enumerated Type An "enum" is a type with a fixed set of elements.

Java - Applets. public class Buttons extends Applet implements ActionListener

Swing UI. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff

Functors - Objects That Act Like Functions

Goals. Lecture 7 More GUI programming. The application. The application D&D 12. CompSci 230: Semester JFrame subclass: ListOWords

IT101. File Input and Output

Introduction to Graphical User Interfaces (GUIs) Lecture 10 CS2110 Fall 2008

Chapter 4: Loops and Files

CS193k, Stanford Handout #16

Question 1. (2 points) What is the difference between a stream and a file?

Events and Exceptions

Transcription:

CASE STUDY 7 A Simple Text Editor Application 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. Figure CS7-1 The text editor window 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 following section presents a summary of the actions performed by each menu item. CS7-1

CS7-2 Case Study 7 A Simple Text Editor Application Figure CS7-2 Menu system for the text editor application File Menu New Open Save 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. 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. 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 Serif SansSerif Italic Bold This radio button menu item changes the text area s font to Monospaced. This radio button menu item changes the text area s font to Serif. This radio button menu item changes the text area s font to SansSerif. This check box menu item changes the text area s style to italic. 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 Figure CS7-3 Text displayed in various fonts and styles Code Listing CS7-1 (TextEditor.java) 1 import java.awt.*; 2 import java.awt.event.*; 3 import javax.swing.*; 4 import java.io.*; 5 6 /** 7 The TextEditor class is a simple text editor. 8 */ 9 10 public class TextEditor extends JFrame 11 { 12 // The following are fields for the menu system. 13 // First, the menu bar 14 private JMenuBar menubar; 15

CS7-4 Case Study 7 A Simple Text Editor Application 16 // The menus 17 private JMenu filemenu; 18 private JMenu fontmenu; 19 20 // The menu items 21 private JMenuItem newitem; 22 private JMenuItem openitem; 23 private JMenuItem saveitem; 24 private JMenuItem saveasitem; 25 private JMenuItem exititem; 26 27 // The radio button menu items 28 private JRadioButtonMenuItem monoitem; 29 private JRadioButtonMenuItem serifitem; 30 private JRadioButtonMenuItem sansserifitem; 31 32 // The checkbox menu items 33 private JCheckBoxMenuItem italicitem; 34 private JCheckBoxMenuItem bolditem; 35 36 private String filename; // To hold the file name 37 private JTextArea editortext; // To display the text 38 private final int NUM_LINES = 20; // Lines to display 39 private final int NUM_CHARS = 40; // Chars per line 40 41 /** 42 Constructor 43 */ 44 45 public TextEditor() 46 { 47 // Set the title. 48 settitle("text Editor"); 49 50 // Specify what happens when the close 51 // button is clicked. 52 setdefaultcloseoperation(jframe.exit_on_close); 53 54 // Create the text area. 55 editortext = new JTextArea(NUM_LINES, NUM_CHARS); 56 57 // Turn line wrapping on. 58 editortext.setlinewrap(true); 59 editortext.setwrapstyleword(true); 60 61 // Create a scroll pane and add the text area to it. 62 JScrollPane scrollpane = new JScrollPane(editorText); 63

Case Study 7 A Simple Text Editor Application CS7-5 64 // Add the scroll pane to the content pane. 65 add(scrollpane); 66 67 // Build the menu bar. 68 buildmenubar(); 69 70 // Pack and display the window. 71 pack(); 72 setvisible(true); 73 } 74 75 /** 76 The buildmenubar method creates a menu bar and 77 calls the createfilemenu method to create the 78 file menu. 79 */ 80 81 private void buildmenubar() 82 { 83 // Build the file and font menus. 84 buildfilemenu(); 85 buildfontmenu(); 86 87 // Create the menu bar. 88 menubar = new JMenuBar(); 89 90 // Add the file and font menus to the menu bar. 91 menubar.add(filemenu); 92 menubar.add(fontmenu); 93 94 // Set the menu bar for this frame. 95 setjmenubar(menubar); 96 } 97 98 /** 99 The buildfilemenu method creates the file menu 100 and populates it with its menu items. 101 */ 102 103 private void buildfilemenu() 104 { 105 // Create the New menu item. 106 newitem = new JMenuItem("New"); 107 newitem.setmnemonic(keyevent.vk_n); 108 newitem.addactionlistener(new NewListener()); 109 110 // Create the Open menu item. 111 openitem = new JMenuItem( Open );

CS7-6 Case Study 7 A Simple Text Editor Application 112 openitem.setmnemonic(keyevent.vk_o); 113 openitem.addactionlistener(new OpenListener()); 114 115 // Create the Save menu item. 116 saveitem = new JMenuItem("Save"); 117 saveitem.setmnemonic(keyevent.vk_s); 118 saveitem.addactionlistener(new SaveListener()); 119 120 // Create the Save As menu item. 121 saveasitem = new JMenuItem("Save As"); 122 saveasitem.setmnemonic(keyevent.vk_a); 123 saveasitem.addactionlistener(new SaveListener()); 124 125 // Create the Exit menu item. 126 exititem = new JMenuItem("Exit"); 127 exititem.setmnemonic(keyevent.vk_x); 128 exititem.addactionlistener(new ExitListener()); 129 130 // Create a menu for the items we just created. 131 filemenu = new JMenu("File"); 132 filemenu.setmnemonic(keyevent.vk_f); 133 134 // Add the items and some separator bars to the menu. 135 filemenu.add(newitem); 136 filemenu.add(openitem); 137 filemenu.addseparator();// Separator bar 138 filemenu.add(saveitem); 139 filemenu.add(saveasitem); 140 filemenu.addseparator();// Separator bar 141 filemenu.add(exititem); 142 } 143 144 /** 145 The buildfontmenu method creates the font menu 146 and populates it with its menu items. 147 */ 148 149 private void buildfontmenu() 150 { 151 // Create the Monospaced menu item. 152 monoitem = new JRadioButtonMenuItem("Monospaced"); 153 monoitem.addactionlistener(new FontListener()); 154 155 // Create the Serif menu item. 156 serifitem = new JRadioButtonMenuItem("Serif"); 157 serifitem.addactionlistener(new FontListener()); 158 159 // Create the SansSerif menu item.

Case Study 7 A Simple Text Editor Application CS7-7 160 sansserifitem = 161 new JRadioButtonMenuItem("SansSerif", true); 162 sansserifitem.addactionlistener(new FontListener()); 163 164 // Group the radio button menu items. 165 ButtonGroup group = new ButtonGroup(); 166 group.add(monoitem); 167 group.add(serifitem); 168 group.add(sansserifitem); 169 170 // Create the Italic menu item. 171 italicitem = new JCheckBoxMenuItem("Italic"); 172 italicitem.addactionlistener(new FontListener()); 173 174 // Create the Bold menu item. 175 bolditem = new JCheckBoxMenuItem("Bold"); 176 bolditem.addactionlistener(new FontListener()); 177 178 // Create a menu for the items we just created. 179 fontmenu = new JMenu("Font"); 180 fontmenu.setmnemonic(keyevent.vk_t); 181 182 // Add the items and some separator bars to the menu. 183 fontmenu.add(monoitem); 184 fontmenu.add(serifitem); 185 fontmenu.add(sansserifitem); 186 fontmenu.addseparator();// Separator bar 187 fontmenu.add(italicitem); 188 fontmenu.add(bolditem); 189 } 190 191 /** 192 Private inner class that handles the event that 193 is generated when the user selects New from 194 the file menu. 195 */ 196 197 private class NewListener implements ActionListener 198 { 199 public void actionperformed(actionevent e) 200 { 201 editortext.settext(""); 202 filename = null; 203 } 204 } 205 206 /** 207 Private inner class that handles the event that

CS7-8 Case Study 7 A Simple Text Editor Application 208 is generated when the user selects Open from 209 the file menu. 210 */ 211 212 private class OpenListener implements ActionListener 213 { 214 public void actionperformed(actionevent e) 215 { 216 int chooserstatus; 217 218 JFileChooser chooser = new JFileChooser(); 219 chooserstatus = chooser.showopendialog(null); 220 if (chooserstatus == JFileChooser.APPROVE_OPTION) 221 { 222 // Get a reference to the selected file. 223 File selectedfile = chooser.getselectedfile(); 224 225 // Get the path of the selected file. 226 filename = selectedfile.getpath(); 227 228 // Open the file. 229 if (!openfile(filename)) 230 { 231 JOptionPane.showMessageDialog(null, 232 "Error reading " + 233 filename, "Error", 234 JOptionPane.ERROR_MESSAGE); 235 } 236 } 237 } 238 239 /** 240 The openfile method opens the file specified by 241 filename and reads its contents into the text 242 area. The method returns true if the file was 243 opened and read successfully, or false if an 244 error occurred. 245 @param filename The name of the file to open. 246 */ 247 248 private boolean openfile(string filename) 249 { 250 boolean success; 251 String inputline, editorstring = ""; 252 FileReader freader; 253 BufferedReader inputfile; 254 255 try

Case Study 7 A Simple Text Editor Application CS7-9 256 { 257 // Open the file. 258 freader = new FileReader(filename); 259 inputfile = new BufferedReader(freader); 260 261 // Read the file contents into the editor. 262 inputline = inputfile.readline(); 263 while (inputline!= null) 264 { 265 editorstring = editorstring + 266 inputline + "\n"; 267 inputline = inputfile.readline(); 268 } 269 editortext.settext(editorstring); 270 271 // Close the file. 272 inputfile.close(); 273 274 // Indicate that everything went OK. 275 success = true; 276 } 277 catch (IOException e) 278 { 279 // Something went wrong. 280 success = false; 281 } 282 283 // Return our status. 284 return success; 285 } 286 } 287 288 /** 289 Private inner class that handles the event that 290 is generated when the user selects Save or Save 291 As from the file menu. 292 */ 293 294 private class SaveListener implements ActionListener 295 { 296 public void actionperformed(actionevent e) 297 { 298 int chooserstatus; 299 300 // If the user selected Save As, or the contents 301 // of the editor have not been saved, use a file 302 // chooser to get the file name. Otherwise, save 303 // the file under the current file name.

CS7-10 Case Study 7 A Simple Text Editor Application 304 305 if (e.getactioncommand() == "Save As" 306 filename == null) 307 { 308 JFileChooser chooser = new JFileChooser(); 309 chooserstatus = chooser.showsavedialog(null); 310 if (chooserstatus == JFileChooser.APPROVE_OPTION) 311 { 312 // Get a reference to the selected file. 313 File selectedfile = 314 chooser.getselectedfile(); 315 316 // Get the path of the selected file. 317 filename = selectedfile.getpath(); 318 } 319 } 320 321 // Save the file. 322 if (!savefile(filename)) 323 { 324 JOptionPane.showMessageDialog(null, 325 "Error saving " + 326 filename, 327 "Error", 328 JOptionPane.ERROR_MESSAGE); 329 } 330 } 331 332 /** 333 The savefile method saves the contents of the 334 text area to a file. The method returns true if 335 the file was saved successfully, or false if an 336 error occurred. 337 @param filename The name of the file. 338 @return true if successful, false otherwise. 339 */ 340 341 private boolean savefile(string filename) 342 { 343 boolean success; 344 String editorstring; 345 FileWriter fwriter; 346 PrintWriter outputfile; 347 348 try 349 { 350 // Open the file. 351 fwriter = new FileWriter(filename);

352 outputfile = new PrintWriter(fwriter); 353 354 // Write the contents of the text area 355 // to the file. 356 editorstring = editortext.gettext(); 357 outputfile.print(editorstring); 358 359 // Close the file. 360 outputfile.close(); 361 362 // Indicate that everything went OK. 363 success = true; 364 } 365 catch (IOException e) 366 { 367 // Something went wrong. 368 success = false; 369 } 370 371 // Return our status. 372 return success; 373 } 374 } 375 376 /** 377 Private inner class that handles the event that 378 is generated when the user selects Exit from 379 the file menu. 380 */ 381 382 private class ExitListener implements ActionListener 383 { 384 public void actionperformed(actionevent e) 385 { 386 System.exit(0); 387 } 388 } 389 390 /** 391 Private inner class that handles the event that 392 is generated when the user selects an item from 393 the font menu. 394 */ 395 396 private class FontListener implements ActionListener 397 { 398 public void actionperformed(actionevent e) 399 { Case Study 7 A Simple Text Editor Application CS7-11

CS7-12 Case Study 7 A Simple Text Editor Application 400 // Get the current font. 401 Font textfont = editortext.getfont(); 402 403 // Retrieve the font name and size. 404 String fontname = textfont.getname(); 405 int fontsize = textfont.getsize(); 406 407 // Start with plain style. 408 int fontstyle = Font.PLAIN; 409 410 // Determine which font is selected. 411 if (monoitem.isselected()) 412 fontname = "Monospaced"; 413 else if (serifitem.isselected()) 414 fontname = "Serif"; 415 else if (sansserifitem.isselected()) 416 fontname = "SansSerif"; 417 418 // Determine whether italic is selected. 419 if (italicitem.isselected()) 420 fontstyle += Font.ITALIC; 421 422 // Determine whether bold is selected. 423 if (bolditem.isselected()) 424 fontstyle += Font.BOLD; 425 426 // Set the font as selected. 427 editortext.setfont(new Font(fontName, 428 fontstyle, fontsize)); 429 } 430 } 431 432 /** 433 main method 434 */ 435 436 public static void main(string[] args) 437 { 438 TextEditor te = new TextEditor(); 439 } 440 }