Download presentation
Presentation is loading. Please wait.
Published byPolly Tate Modified over 9 years ago
1
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 25 – Ticket Information Application Introducing Sequential-Access Files Outline 25.1 Test-Driving the Write Event and Ticket Information Applications 25.2Data Hierarchy 25.3Files and Streams 25.4Creating the Write Event Application: Writing to a File 25.5Creating the Ticket Information Application 25.6Using the finally block 25.7Wrap-Up
2
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 2 Objectives In this tutorial, you will learn to: –Create, read from, write to and update files. –Understand a computer’s data hierarchy. –Become familiar with sequential-access file processing. –Use the FileReader with BufferedReader capabilities to read a line of text from sequential-access files. –Use the FileWriter with PrintWriter capabilities to write text to sequential-access files. –Use the finally clause with exception handling to ensure that certain actions are always performed.
3
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 3 25.1 Test-Driving the Write Event and Ticket Information Applications
4
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 4 25.1 Test-Driving the Write Event and Ticket Information Applications (Cont.)
5
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 5 25.1 Test-Driving the Write Event and Ticket Information Applications (Cont.) Figure 25.1 Ticket Information application’s GUI. JSpinner JComboBox lists any events JTextArea displays event details
6
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 6 25.1 Test-Driving the Write Event and Ticket Information Applications (Cont.) Run the Ticket Information application – Type java TicketInformation JSpinner displays the day of the current month Getting event information – Select day that has an event – JComboBox displays first event of day – Time, price and description appear in Description: JTextArea
7
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 7 25.1 Test-Driving the Write Event and Ticket Information Applications (Cont.) Figure 25.2 Ticket Information application displaying event information. Event information displayed
8
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 8 25.1 Test-Driving the Write Event and Ticket Information Applications (Cont.) Opening a file – Click the Load File… JButton – Open calender.txt – Load File… JButton is disabled – All other components enabled
9
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 9 25.1 Test-Driving the Write Event and Ticket Information Applications (Cont.) Figure 25.3 The Write Event application enables user to store event data. JTextArea displays event description JTextField for price of event JSpinner for day of event JSpinner for time of event JTextField for name of event Open File… JButton used to open a file that will store the event data
10
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 10 25.1 Test-Driving the Write Event and Ticket Information Applications (Cont.) Figure 25.4 Dialog enables users to specify a file that will store event data.
11
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 11 25.1 Test-Driving the Write Event and Ticket Information Applications (Cont.) Figure 25.5 Adding an event to calendar.txt
12
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 12 25.1 Test-Driving the Write Event and Ticket Information Applications (Cont.) Figure 25.6 Entering another event and closing the file.
13
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 13 25.1 Test-Driving the Write Event and Ticket Information Applications (Cont.) Figure 25.7 Using the Pick an event: JComboBox to select from multiple events occurring on the same day.
14
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 14 25.2 Data Hierarchy Data hierarchy –From bits up to larger data structures Characters –Digits, letters and special symbols Character set –Set of characters used to write applications and represent data items on a computer
15
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 15 25.2 Data Hierarchy (Cont.) Figure 25.8 Data hierarchy.
16
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 16 25.2 Data Hierarchy (Cont.) Bits –Smallest data item a computer can support –Short for binary digit Can hold one of two values –0 –1 Characters are represented as patterns of bits Bytes –8 bits –Characters in Java are Unicode 2 bytes (16 bits)
17
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 17 25.2 Data Hierarchy (Cont.) Fields –Group of characters that conveys some meaning Record –Group of related fields File –Group of related records Record key –Identifies record as being part of some entity –Distinguishes record from all other records –One field in each record
18
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 18 25.2 Data Hierarchy (Cont.) Sequential file –Records stored in order by record-key field Database –Group or related files –Database management system used to design and manage databases
19
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 19 25.3 Files and Streams Figure 25.9 Java’s conceptual view of an n-byte file. Streams –Object that contains of sequence of characters –Java views files as a sequential stream of bytes
20
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 20 25.3 Files and Streams The java.io package –BufferedReader class Used for text input from a file Can read lines of text Don’t know how to read from a file –Combine FileReader class (used to open a file) and BufferedReader class to read from a file –PrintWriter class Used for text output to a file Don’t know how to write to a file Combine FileWriter class (used to open a file) and PrintWriter class for write to a file
21
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 21 25.4 Creating the Write Event Application: Writing to a File When the user clicks the Open File… JButton Display a JFileChooser dialog Retrieve the file (from the JFileChooser) as selected by the user Open the selected file for writing Disable the Open File… JButton Enable the Enter JButton Enable the Close File JButton Reset input fields (priceJTextField, eventJTextField and descriptionJTextArea) When the user clicks the Enter JButton Add the day of the event and a newline character to the file Add the time of the event and a newline character to the file Add the price of the event and a newline character to the file Add the name of the event and a newline character to the file Add a description of the event and a newline character to the file Reset input fields (priceJTextField, eventJTextField and descriptionJTextArea) When the user clicks the Close File JButton Close the file Disable Enter JButton Enable Open File… JButton Disable Close File JButton Reset input fields (priceJTextField, eventJTextField and descriptionJTextArea)
22
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 22 25.4 Creating the Write Event Application: Writing to a File (Cont.)
23
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 23 25.4 Creating the Write Event Application: Writing to a File (Cont.)
24
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 24 25.4 Creating the Write Event Application: Writing to a File (Cont.) Figure 25.11 Importing the java.io package into the WriteEvent class. Importing the java.io package Figure 25.12 Declaring a PrintWriter object. Declaring a PrintWriter object
25
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 25 25.4 Creating the Write Event Application: Writing to a File (Cont.) Figure 25.13 Displaying the JFileChooser dialog and retrieving the result. Displaying the JFileChooser dialog
26
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 26 25.4 Creating the Write Event Application: Writing to a File (Cont.) JFileChooser –Allows user to select file from disk If file does not exist, a new file will be created –setDialogTitle – sets title bar string of JFileChooser –showOpenDialog – displays dialog for opening a file –JFileChooser.CANCEL_OPTION int constant returned if user clicks Cancel in JFileChooser –JFileChooser.APPROVE_OPTION int constant returned if user clicks OK in JFileChooser –JFileChooser.ERROR_OPTION int constant returned if an error occurs
27
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 27 25.4 Creating the Write Event Application: Writing to a File (Cont.) Figure 25.14 Exiting the method if the user clicks the Cancel JButton. If the user clicks Cancel JButton, the method returns
28
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 28 25.4 Creating the Write Event Application: Writing to a File (Cont.) Figure 25.15 Retrieving the file selected by the user. Getting the selected file getSelectedFile method of JFileChooser –Returns File object that represents the file, directory path and name of file chosen by user
29
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 29 25.4 Creating the Write Event Application: Writing to a File (Cont.) Figure 25.16 Retrieving the name of the file using the getName method. Retrieving the name of the selected file
30
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 30 25.4 Creating the Write Event Application: Writing to a File (Cont.) Figure 25.17 Validating the file name. Checking for a missing file name
31
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 31 25.4 Creating the Write Event Application: Writing to a File (Cont.) Figure 25.18 Opening the file to which the information will be written. Create a FileWriter and pass it to PrintWriter constructor
32
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 32 25.4 Creating the Write Event Application: Writing to a File (Cont.) Figure 25.19 Changing the state of the JButton s.
33
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 33 25.4 Creating the Write Event Application: Writing to a File (Cont.) Figure 25.20 Displaying a JOptionPane if an IOException is caught. Catch any IOException thrown from the try block
34
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 34 25.4 Creating the Write Event Application: Writing to a File (Cont.) Figure 25.21 Calling method resetUserInput. Clearing the user input components
35
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 35 25.4 Creating the Write Event Application: Writing to a File (Cont.) Figure 25.22 WriteEvent application with opening files capability.
36
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 36 25.4 Creating the Write Event Application: Writing to a File (Cont.) Figure 25.23 Creating a file.
37
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 37 25.4 Creating the Write Event Application: Writing to a File (Cont.) Figure 25.24 PrintWriter writing to a file. Writing data to the file
38
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 38 25.4 Creating the Write Event Application: Writing to a File (Cont.) PrintWriter class –println method Writes its String argument to the file Figure 25.25 Adding the price, event name and event description to the file.
39
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 39 25.4 Creating the Write Event Application: Writing to a File (Cont.) Figure 25.26 Closing the PrintWriter. Closing the PrintWriter PrintWriter class –close method Closes the stream that writes to the file
40
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 40 25.4 Creating the Write Event Application: Writing to a File (Cont.) Figure 25.27 Write Event application executing.
41
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 41 25.4 Creating the Write Event Application: Writing to a File (Cont.) Figure 25.28 Open File for Write Event dialog displaying contents of the template Write Event application’s directory.
42
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 42 25.4 Creating the Write Event Application: Writing to a File (Cont.) Figure 25.29 Adding the Arts and Crafts Fair event to test.txt.
43
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 43 25.4 Creating the Write Event Application: Writing to a File (Cont.) Figure 25.30 Sequential-access file generated by Write Event application. Data written to file
44
2004 Prentice Hall, Inc. All rights reserved. Outline 44 WriteEvent.java (1 of 13) 1 // Tutorial 25: WriteEvent.java 2 // This application writes information about an event on a given 3 // date to a file. 4 import java.awt.*; 5 import java.awt.event.*; 6 import java.io.*; 7 import java.text.*; 8 import java.util.Date; 9 import javax.swing.*; 10 import javax.swing.event.*; 11 12 public class WriteEvent extends JFrame 13 { 14 // JLabel and JSpinner to display day of month 15 private JLabel dayJLabel; 16 private JSpinner dayJSpinner; 17 18 // JLabel, JSpinner and JSpinner.DateEditor to display time 19 private JLabel timeJLabel; 20 private JSpinner timeJSpinner; 21 22 // JLabel and JTextField to display price 23 private JLabel priceJLabel; 24 private JTextField priceJTextField; 25 Importing the package java.io
45
2004 Prentice Hall, Inc. All rights reserved. Outline 45 WriteEvent.java (2 of 13) 26 // JLabel and JTextField to display event name 27 private JLabel eventJLabel; 28 private JTextField eventJTextField; 29 30 // JLabel and JTextArea to display event description 31 private JLabel descriptionJLabel; 32 private JTextArea descriptionJTextArea; 33 34 // JButtons to allow user to write to files 35 private JButton openFileJButton; 36 private JButton enterJButton; 37 private JButton closeFileJButton; 38 39 // PrintWriter to write to files 40 private PrintWriter output; 41 42 // no-argument constructor 43 public WriteEvent() 44 { 45 createUserInterface(); 46 } 47 48 // create and position GUI components; register event handlers 49 private void createUserInterface() 50 { Declaring a new PrintWriter object
46
2004 Prentice Hall, Inc. All rights reserved. Outline 46 WriteEvent.java (3 of 13) 51 // get content pane for attaching GUI components 52 Container contentPane = getContentPane(); 53 54 // enable explicit positioning of GUI components 55 contentPane.setLayout( null ); 56 57 // set up dayJLabel 58 dayJLabel = new JLabel(); 59 dayJLabel.setBounds( 20, 16, 75, 23 ); 60 dayJLabel.setText( "Day:" ); 61 contentPane.add( dayJLabel ); 62 63 // set up dayJSpinner 64 dayJSpinner = new JSpinner ( 65 new SpinnerNumberModel( 1, 1, 31, 1); 66 dayJSpinner.setBounds( 108, 16, 150, 23 ); 67 contentPane.add( dayJSpinner ); 68 69 // set up timeJLabel 70 timeJLabel = new JLabel(); 71 timeJLabel.setBounds( 20, 46, 75, 23 ); 72 timeJLabel.setText( "Time:" ); 73 contentPane.add( timeJLabel ); 74
47
2004 Prentice Hall, Inc. All rights reserved. Outline 47 WriteEvent.java (4 of 13) 75 // set up timeJSpinner 76 timeJSpinner = new JSpinner( new SpinnerDateModel() ); 77 timeJSpinner.setBounds( 108, 46, 150, 23 ); 78 timeJSpinner.setEditor( 79 new JSpinner.DateEditor( timeJSpinner, "HH:mm" ) ); 80 contentPane.add( timeJSpinner ); 81 82 // set up priceJLabel 83 priceJLabel = new JLabel(); 84 priceJLabel.setBounds( 20, 76, 75, 23 ); 85 priceJLabel.setText( "Price:" ); 86 contentPane.add( priceJLabel ); 87 88 // set up priceJTextField 89 priceJTextField = new JTextField(); 90 priceJTextField.setBounds( 108, 76, 150, 23 ); 91 contentPane.add( priceJTextField ); 92 93 // set up eventJLabel 94 eventJLabel = new JLabel(); 95 eventJLabel.setBounds( 20, 106, 75, 23 ); 96 eventJLabel.setText( "Event:" ); 97 contentPane.add( eventJLabel ); 98
48
2004 Prentice Hall, Inc. All rights reserved. Outline 48 WriteEvent.java (5 of 13) 99 // set up eventJTextField 100 eventJTextField = new JTextField(); 101 eventJTextField.setBounds( 108, 106, 150, 23 ); 102 contentPane.add( eventJTextField ); 103 104 // set up descriptionJLabel 105 descriptionJLabel = new JLabel(); 106 descriptionJLabel.setBounds( 20, 136, 75, 23 ); 107 descriptionJLabel.setText( "Description:" ); 108 contentPane.add( descriptionJLabel ); 109 110 // set up descriptionJTextArea 111 descriptionJTextArea = new JTextArea(); 112 descriptionJTextArea.setBounds( 108, 136, 150, 125 ); 113 descriptionJTextArea.setLineWrap( true ); 114 descriptionJTextArea.setWrapStyleWord( true ); 115 contentPane.add( descriptionJTextArea ); 116 117 // set up openFileJButton 118 openFileJButton = new JButton(); 119 openFileJButton.setBounds( 5, 275, 100, 40 ); 120 openFileJButton.setText( "Open File..." ); 121 contentPane.add( openFileJButton ); 122 openFileJButton.addActionListener( 123
49
2004 Prentice Hall, Inc. All rights reserved. Outline 49 WriteEvent.java (6 of 13) 124 new ActionListener() // anonymous inner class 125 { 126 // event handler called when openFileJButton is clicked 127 public void actionPerformed( ActionEvent event ) 128 { 129 openFileJButtonActionPerformed( event ); 130 } 131 132 } // end anonymous inner class 133 134 ); // end call to addActionListener 135 136 // set up enterJButton 137 enterJButton = new JButton(); 138 enterJButton.setBounds( 106, 275, 80, 40 ); 139 enterJButton.setText( "Enter" ); 140 enterJButton.setEnabled( false ); 141 contentPane.add( enterJButton ); 142 enterJButton.addActionListener( 143 144 new ActionListener() // anonymous inner class 145 { 146 // event handler called when enterJButton is clicked 147 public void actionPerformed( ActionEvent event ) 148 {
50
2004 Prentice Hall, Inc. All rights reserved. Outline 50 WriteEvent.java (7 of 13) 149 enterJButtonActionPerformed( event ); 150 } 151 152 } // end anonymous inner class 153 154 ); // end call to addActionListener 155 156 // set up closeFileJButton 157 closeFileJButton = new JButton(); 158 closeFileJButton.setBounds( 186, 275, 95, 40 ); 159 closeFileJButton.setText( "Close File" ); 160 closeFileJButton.setEnabled( false ); 161 contentPane.add( closeFileJButton ); 162 closeFileJButton.addActionListener( 163 164 new ActionListener() // anonymous inner class 165 { 166 // event handler called when closeFileJButton is clicked 167 public void actionPerformed( ActionEvent event ) 168 { 169 closeFileJButtonActionPerformed( event ); 170 } 171 172 } // end anonymous inner class 173
51
2004 Prentice Hall, Inc. All rights reserved. Outline 51 WriteEvent.java (8 of 13) 174 ); // end call to addActionListener 175 176 // set properties of application's window 177 setTitle( "WriteEvent" ); // set title bar string 178 setSize( 290, 345 ); // set window size 179 setVisible( true ); // display window 180 181 } // end method createUserInterface 182 183 // open a file for writing 184 private void openFileJButtonActionPerformed( ActionEvent event ) 185 { 186 // display file dialog so user can select file to open 187 JFileChooser fileChooser = new JFileChooser(); 188 fileChooser.setDialogTitle( "Open File for Write Event" ); 189 int result = fileChooser.showOpenDialog( this ); 190 191 // if user clicked Cancel JButton on dialog, return 192 if ( result == JFileChooser.CANCEL_OPTION ) 193 { 194 return; // exit method openFileJButtonActionPerformed 195 } 196 Displaying the JFileChooser dialog User clicks Cancel JButton Exit the method
52
2004 Prentice Hall, Inc. All rights reserved. Outline 52 WriteEvent.java (9 of 13) 197 // get selected file 198 File selectedFile = fileChooser.getSelectedFile(); 199 200 // get selected file name 201 String fileName = selectedFile.getName(); 202 203 // display error if file name invalid 204 if ( fileName.equals( "" ) ) 205 { 206 JOptionPane.showMessageDialog( this, "File name missing.", 207 "File Name Missing", JOptionPane.ERROR_MESSAGE ); 208 } 209 else 210 { 211 // open file 212 try 213 { 214 // append information to fileName 215 FileWriter outputFile = 216 new PrintWriter( selectedFile, true ); 217 output = new BufferedWriter( outputFile ); 218 219 // change state of JButtons 220 openFileJButton.setEnabled( false ); 221 enterJButton.setEnabled( true ); 222 closeFileJButton.setEnabled( true ); Get the selected file Get the selected file name Create a FileWriter and pass it to the PrintWriter constructor Validate the file name
53
2004 Prentice Hall, Inc. All rights reserved. Outline 53 WriteEvent.java (10 of 13) 223 } 224 catch ( IOException exception ) 225 { 226 JOptionPane.showMessageDialog( this, 227 “Cannot open the file“ + fileName + “.”, "Error", 228 JOptionPane.ERROR_MESSAGE ); 229 } 230 231 } // end else 232 233 // reset JButtons to initial states 234 resetUserInput(); 235 236 } // end method openFileJButtonActionPerformed 237 238 // save data entered to specified file 239 private void enterJButtonActionPerformed( ActionEvent event ) 240 { 241 // write day to file 242 output.println( dayJSpinner.getvalue() ); 243 244 // retrieve time entered by user 245 String time = String.valueOf( timeJSpinner.getValue() ); 246 time = time.substring( 11, 16 ); 247 Catch any IOException thrown from the try block Write data to the file
54
2004 Prentice Hall, Inc. All rights reserved. Outline 54 WriteEvent.java (11 of 13) 248 // write time to file followed by a newline character 249 output.println( time ); 250 251 // write price to file followed by a newline character 252 output.println( "$" + priceJTextField.getText() ); 253 254 // write event name to file followed by a newline character 255 output.println( eventJTextField.getText() ); 256 257 // write event description to file 258 output.println( descriptionJTextArea.getText() ); 259 260 // clear JTextFields 261 resetUserInput(); 262 263 } // end method enterJButtonActionPerformed 264 265 // file is closed after user is finished with it 266 private void closeFileJButtonActionPerformed( ActionEvent event ) 267 { 268 // close file 269 output.close(); 270 Write data to the file Close the file
55
2004 Prentice Hall, Inc. All rights reserved. Outline 55 WriteEvent.java (12 of 13) 271 // reset state of JButtons 272 enterJButton.setEnabled( false ); 273 openFileJButton.setEnabled( true ); 274 closeFileJButton.setEnabled( false ); 275 276 // clear JTextFields 277 resetUserInput(); 278 279 } // end method closeFileJButtonActionPerformed 280 281 // clear JTextFields 282 private void resetUserInput() 283 { 284 priceJTextField.setText( "" ); 285 eventJTextField.setText( "" ); 286 descriptionJTextArea.setText( "" ); 287 288 } // end method resetUserInput 289
56
2004 Prentice Hall, Inc. All rights reserved. Outline 56 WriteEvent.java (13 of 13) 290 // main method 291 public static void main( String[] args ) 292 { 293 WriteEvent application = new WriteEvent(); 294 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 295 296 } // end method main 297 298 } // end class WriteEvent
57
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 57 25.5 Building the Ticket Information Application When the user selects a date from the dateJSpinner Retrieve the day selected in dateJSpinner Open calendar.txt file to read from While there are events left in the file If the current event is for the day selected by the user Store in array daysEvents the event information Increment eventNumber, which contains the number of events for the selected day Read the next event’s information Close the file If events are scheduled for that day Add each event to eventJComboBox Else Display "- No Events -" in the eventJComboBox Display "No events today." in the descriptionJTextArea When the user selects an event from the eventJComboBox Retrieve index of selected item in the eventJComboBox Display event information in the descriptionJTextArea
58
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 58 25.5 Building the Ticket Information Application (Cont.)
59
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 59 25.5 Building the Ticket Information Application (Cont.) Figure 25.33 Declaring an instance variable in the Ticket Information application. Declare a BufferedReader object
60
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 60 25.5 Building the Ticket Information Application (Cont.) Figure 25.34 Invoking the createEventList method. Calling the createEventList method
61
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 61 25.5 Building the Ticket Information Application (Cont.) Figure 25.35 Calling the extractData method and clearing the eventJComboBox. The extractData method will read events from calendar.txt
62
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 62 25.5 Building the Ticket Information Application (Cont.) removeAllItems method of JComboBox –Removes all items in the JComboBox Figure 25.36 Displaying the events scheduled for the specified day. Indicating that events are scheduled for the day Extracting the event name from the array and displaying it in the eventJComboBox Indicating that no events are scheduled for the day
63
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 63 25.5 Building the Ticket Information Application (Cont.) Figure 25.37 Declaring variables in the extractData method.
64
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 64 25.5 Building the Ticket Information Application (Cont.) Figure 25.38 Using a BufferedReader object to read data from a sequential-access file. Read a line from the file Create a FileReader and pass it to the BufferedReader constructor
65
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 65 25.5 Building the Ticket Information Application (Cont.) BufferedReader object –readLine method Reads characters from a stream, up to and including a newline Returns characters as a String
66
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 66 25.5 Building the Ticket Information Application (Cont.) Figure 25.39 Reading through each line in a file. Check to see if end of file has been reached
67
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 67 25.5 Building the Ticket Information Application (Cont.) Store event information in a row of the array Figure 25.40 Sequentially reading event entries from the file.
68
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 68 25.5 Building the Ticket Information Application (Cont.) Figure 25.41 Finding the next date in the file.
69
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 69 25.5 Building the Ticket Information Application (Cont.) Figure 25.42 Displaying an error message if there is an error reading from the file.
70
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 70 25.6 Using the finally block finally block –Typically contains resource-release code –Always executes Executes if no exception is thrown Executes if an exception is thrown
71
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 71 25.6 Using the finally block (Cont.) Figure 25.43 Adding a finally block to your code. Code in the finally block always executes
72
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 72 25.6 Using the finally block (Cont.) Close the input file Figure 25.44 Closing the BufferedReader file.
73
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 73 25.6 Using the finally block (Cont.) Figure 25.45 Ticket Information application with event names.
74
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 74 25.6 Using the finally block (Cont.) Figure 25.46 Displaying event information in descriptionJTextArea.
75
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 75 25.6 Using the finally block (Cont.) Figure 25.47 Completed Ticket Information application.
76
2004 Prentice Hall, Inc. All rights reserved. Outline 76 Ticket- Information.java (1 of 12) 1 // Tutorial 25: TicketInformation.java 2 // This program reads information about events on different dates 3 // from a file. 4 import java.awt.*; 5 import java.awt.event.*; 6 import java.text.*; 7 import java.util.Date; 8 import javax.swing.*; 9 import javax.swing.event.*; 10 import java.io.*; 11 12 public class TicketInformation extends JFrame 13 { 14 // JLabel, JSpinner, and DateEditor to display date 15 private JLabel selectDateJLabel; 16 private JSpinner dateJSpinner; 17 18 // JLabel and JComboBox to display day's events 19 private JLabel pickEventJLabel; 20 private JComboBox eventJComboBox; 21 22 // JLabel and JTextArea to display details of events 23 private JLabel descriptionJLabel; 24 private JTextArea descriptionJTextArea; 25
77
2004 Prentice Hall, Inc. All rights reserved. Outline 77 Ticket- Information.java (2 of 12) 26 // BufferedReader to read data from a file 27 private BufferedReader input; 28 29 // File selected by user 30 private File calendarFile; 31 32 // instance variables to store event information and number 33 private String[][] daysEvents = new String[ 10 ][ 5 ]; 34 private int eventNumber; 35 36 // no-argument constructor 37 public TicketInformation() 38 { 39 createUserInterface(); 40 41 createEventList(); // read file and display events on given day 42 } 43 44 // create and position GUI components; register event handlers 45 private void createUserInterface() 46 { 47 // get content pane for attaching GUI components 48 Container contentPane = getContentPane(); 49 Declare a BufferedReader object
78
2004 Prentice Hall, Inc. All rights reserved. Outline 78 Ticket- Information.java (3 of 12) 50 // enable explicit positioning of GUI components 51 contentPane.setLayout( null ); 52 53 // set up dateJLabel 54 dateJLabel = new JLabel(); 55 dateJLabel.setBounds( 16, 16, 121, 23 ); 56 dateJLabel.setText( "Select the day (1-31):" ); 57 contentPane.add( dateJLabel ); 58 59 // set up dateJSpinner 60 dateJSpinner = new JSpinner( 61 new SpinnerNumberModel( 1, 1, 31, 1 ) ); 62 dateJSpinner.setBounds( 147, 16, 119, 23 ); 63 contentPane.add( dateJSpinner ); 64 dateJSpinner.addChangeListener( 65 66 new ChangeListener() // anonymous inner class 67 { 68 // event handler called when dateJSpinner is changed 69 public void stateChanged( ChangeEvent event ) 70 { 71 dateJSpinnerStateChanged( event ); 72 } 73 74 } // end anonymous inner class
79
2004 Prentice Hall, Inc. All rights reserved. Outline 79 Ticket- Information.java (4 of 12) 75 76 ); // end call to addActionListener 77 78 // set up eventJLabel 79 eventJLabel = new JLabel(); 80 eventJLabel.setBounds( 16, 67, 100, 23 ); 81 eventJLabel.setText( "Pick an event: " ); 82 contentPane.add( eventJLabel ); 83 84 // set up eventJComboBox 85 eventJComboBox = new JComboBox(); 86 eventJComboBox.setBounds( 16, 94, 250, 23 ); 87 eventJComboBox.addItem( "- No Events -" ); 88 contentPane.add( eventJComboBox ); 89 eventJComboBox.addActionListener( 90 91 new ActionListener() // anonymous inner class 92 { 93 // event handler called when eventJComboBox is changed 94 public void actionPerformed( ActionEvent event ) 95 { 96 eventJComboBoxActionPerformed( event ); 97 } 98 99 } // end anonymous inner class
80
2004 Prentice Hall, Inc. All rights reserved. Outline 80 Ticket- Information.java (5 of 12) 100 101 ); // end call to addActionListener 102 103 // set up descriptionJLabel 104 descriptionJLabel = new JLabel(); 105 descriptionJLabel.setBounds( 16, 141, 100, 23 ); 106 descriptionJLabel.setText( "Description: " ); 107 contentPane.add( descriptionJLabel ); 108 109 // set up descriptionJTextArea 110 descriptionJTextArea = new JTextArea(); 111 descriptionJTextArea.setBounds( 16, 168, 250, 125 ); 112 descriptionJTextArea.setText( "No events today." ); 113 descriptionJTextArea.setLineWrap( true ); 114 descriptionJTextArea.setWrapStyleWord( true ); 115 descriptionJTextArea.setEditable( false ); 116 contentPane.add( descriptionJTextArea ); 117 118 // set properties of application's window 119 setTitle( "Ticket Information" ); // set title bar string 120 setSize( 292, 340 ); // set window size 121 setVisible( true ); // display window 122 123 } // end method createUserInterface 124
81
2004 Prentice Hall, Inc. All rights reserved. Outline 81 Ticket- Information.java (6 of 12) 125 // read event information from a file for a given date 126 private void dateJSpinnerStateChanged( ChangeEvent event ) 127 { 128 createEventList(); 129 130 } // end method dateJSpinnerStateChanged 131 132 // display event information 133 private void eventJComboBoxActionPerformed( ActionEvent event ) 134 { 135 int eventNumber = eventJComboBox.getSelectedIndex(); 136 descriptionJTextArea.setText( 137 daysEvents[ eventNumber ][ 1 ] + "\n" + // time 138 daysEvents[ eventNumber ][ 2 ] + "\n" + // price 139 daysEvents[ eventNumber ][ 4 ] ); // description 140 141 } // end method eventJComboBoxActionPerformed 142 143 // read events for current day and display events in application 144 private void createEventList() 145 { 146 // get data from file 147 extractData(); 148 Create a list of events when the dateJSpinner is changed Extract the data from the file Display the event information in description- JTextArea
82
2004 Prentice Hall, Inc. All rights reserved. Outline 82 Ticket- Information.java (7 of 12) 149 // remove all information from last date 150 eventJComboBox.removeAllItems(); 151 descriptionJTextArea.setText( "" ); 152 153 // if there are events scheduled for the current day 154 if ( eventNumber > 0 ) 155 { 156 // add events to the eventJComboBox 157 for ( int x = 0; x < eventNumber; x++ ) 158 { 159 eventJComboBox.addItem( daysEvents[ x ][ 3 ] ); 160 } 161 } 162 else // no events for the day 163 { 164 eventJComboBox.addItem( "- No Events -" ); 165 descriptionJTextArea.setText( "No events today." ); 166 } 167 168 } // end method createEventList 169 170 // read data from file 171 private void extractData() 172 { 173 eventNumber = 0; Add the events for the day to eventJComboBox
83
2004 Prentice Hall, Inc. All rights reserved. Outline 83 Ticket- Information.java (8 of 12) 174 175 // get date from dateJSpinner and format 176 Integer date = ( Integer ) dateJSpinner.getValue(); 177 String currentDate = String.valueOf( date ); 178 179 // initialize daysEvents array 180 initialize(); 181 182 // find and display events for current date 183 try 184 { 185 // get file 186 calendarFile = new File( "calendar.txt" ); 187 188 // open file 189 FileReader currentFile = new FileReader( calendarFile ); 190 input = new BufferedReader( currentFile ); 191 192 // read a line from the file 193 String contents = input.readLine(); 194 195 // while more lines are in the file 196 while ( contents != null ) 197 { Get the date from the dateJSpinner Create a FileReader and pass it to BufferedReader constructor
84
2004 Prentice Hall, Inc. All rights reserved. Outline 84 Ticket- Information.java (9 of 12) 198 // if day selected is equal to the day read from the file 199 if ( contents.equals( currentDate ) ) 200 { 201 // read event information 202 daysEvents[ eventNumber ][ 0 ] = contents; 203 daysEvents[ eventNumber ][ 1 ] = input.readLine(); 204 daysEvents[ eventNumber ][ 2 ] = input.readLine(); 205 daysEvents[ eventNumber ][ 3 ] = input.readLine(); 206 daysEvents[ eventNumber ][ 4 ] = input.readLine(); 207 eventNumber++; 208 } 209 else // if date was not equal 210 { 211 // move to next date in file 212 for ( int x = 0; x < 4; x++ ) 213 { 214 input.readLine(); 215 } 216 } 217 218 // read a line from the file 219 contents = input.readLine(); 220 221 } // end while 222 } Store the event information in a two-dimensional array Search the entire file
85
2004 Prentice Hall, Inc. All rights reserved. Outline 85 Ticket- Information.java (10 of 12) 223 catch ( IOException exception ) 224 { 225 JOptionPane.showMessageDialog( this, 226 "Please make sure the file exists and is of the " + 227 "right format.", "I/O Error", 228 JOptionPane.ERROR_MESSAGE ); 229 230 // disable components 231 eventJComboBox.setEnabled( false ); 232 dateJSpinner.setEnabled( false ); 233 } 234 finally // close the file 235 { 236 // close the file 237 try 238 { 239 input.close(); 240 } 241 catch( IOException exception ) 242 { 243 JOptionPane.showMessageDialog( this, 244 "Please make sure the file exists and is of the " + 245 "right format.", "I/O Error", 246 JOptionPane.ERROR_MESSAGE ); 247 } 248 } Closing the file
86
2004 Prentice Hall, Inc. All rights reserved. Outline 86 Ticket- Information.java (11 of 12) 249 250 } // end method extractData 251 252 // initialize daysEvents array 253 private void initialize() 254 { 255 // for each of ten possible events per day 256 for ( int i = 0; i <= 9; i++ ) 257 { 258 // for each of five fields per event 259 for ( int j = 0; j <= 4; j++ ) 260 { 261 daysEvents[ i ][ j ] = ""; 262 } 263 } 264 265 daysEvents[ 0 ][ 3 ] = "- No Events -"; 266 daysEvents[ 0 ][ 4 ] = "No events today."; 267 268 } // end method initialize 269
87
2004 Prentice Hall, Inc. All rights reserved. Outline 87 Ticket- Information.java (12 of 12) 270 // main method 271 public static void main( String[] args ) 272 { 273 TicketInformation application = new TicketInformation(); 274 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 275 276 } // end method main 277 278 } // end class TicketInformation
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.