34
14 Files and Streams OBJECTIVES In this chapter you will learn: To create, read, write and update files. To use class File to retrieve information about files and directories. The Java input/output stream class hierarchy. The differences between text files and binary files. Sequential-access file processing. To use classes Scanner and Formatter to process text files. To use the FileInputStream and FileOutputStream classes. To use a JFileChooser dialog. To use the ObjectInputStream and ObjectOutputStream classes. I can only assume that a “Do Not File” document is filed in a “Do Not File” file. —Senator Frank Church Senate Intelligence Subcommittee Hearing, 1975 Consciousness … does not appear to itself chopped up in bits. … A “river” or a “stream” are the metaphors by which it is most naturally described. —William James I read part of it all the way through. —Samuel Goldwyn A great memory does not make a philosopher, any more than a dictionary can be called grammar. —John Henry, Cardinal Newman

Jhtp7 SSM 14

Embed Size (px)

Citation preview

  • 14

    Files and

    Streams

    OB J ECT IVES

    In this chapter you will learn:

    To create, read, write and update les.

    To use class File to retrieve information about les and

    directories.

    The Java input/output stream class hierarchy.

    The differences between text les and binary les.

    Sequential-access le processing.

    To use classes Scanner and Formatter to process

    text les.

    To use the FileInputStream and

    FileOutputStream classes.

    To use a JFileChooser dialog.

    To use the ObjectInputStream and

    ObjectOutputStream classes.

    I can only assume that a Do

    Not File document is led

    in a Do Not File le.

    Senator Frank Church

    Senate Intelligence

    Subcommittee Hearing, 1975

    Consciousness does not

    appear to itself chopped up

    in bits. A river or a

    stream are the metaphors

    by which it is most naturally

    described.

    William James

    I read part of it all the way

    through.

    Samuel Goldwyn

    A great memory does not

    make a philosopher, any

    more than a dictionary can

    be called grammar.

    John Henry, Cardinal

    Newman

  • 2 Chapter 14 Files and Streams

    Student Solution Exercises

    14.6 Fill in the blanks in each of the following statements:

    a) Computers store large amounts of data on secondary storage devices as .

    ANS: files

    b) A(n) is composed of several fields.

    ANS: record

    c) To facilitate the retrieval of specific records from a file, one field in each record is chosen

    as a(n) .

    ANS: record key

    d) Files that are created using byte-based streams are referred to as files, while

    files created using character-based streams are referred to as files.

    ANS: binary, text

    e) The standard stream objects are , and .

    ANS: System.in, System.out, System.err

    14.7 Determine which of the following statements are true and which are false. If false, explain

    why.

    a) The impressive functions performed by computers essentially involve the manipulation

    of zeros and ones.

    ANS: True.

    b) People specify programs and data items as characters. Computers then manipulate and

    process these characters as groups of zeros and ones.

    ANS: True.

    c) Data items represented in computers form a data hierarchy in which data items become

    larger and more complex as we progress from fields to characters to bits and so on.

    ANS: False. Data becomes more complex as we progress from bits to characters to fields,

    and so on.

    d) A record key identifies a record as belonging to a particular field.

    ANS: False. A record key identifies a record as belonging to a particular person or entity.

    e) Companies store all their information in a single file to facilitate computer processing

    of the information. When a program creates a file, the file is retained by the computer

    for future reference.

    ANS: False. Companies typically store information in multiple files.

    14.8 (File Matching) Self-Review Exercise 14.3 asks the reader to write a series of single state-

    ments. Actually, these statements form the core of an important type of file-processing program,

    namely, a file-matching program. In commercial data processing, it is common to have several files

    in each application system. In an accounts receivable system, for example, there is generally amaster

    file containing detailed information about each customer, such as the customers name, address,

    telephone number, outstanding balance, credit limit, discount terms, contract arrangements and

    possibly a condensed history of recent purchases and cash payments.

    As transactions occur (i.e., sales are made and payments arrive in the mail), information about

    them is entered into a le. At the end of each business period (a month for some companies, a

    week for others, and a day in some cases), the le of transactions (called "trans.txt") is applied to

    the master le (called "oldmast.txt") to update each accounts purchase and payment record.

    During an update, the master le is rewritten as the le "newmast.txt", which is then used at the

    end of the next business period to begin the updating process again.

    File-matching programs must deal with certain problems that do not arise in single-le pro-

    grams. For example, a match does not always occur. If a customer on the master le has not made

    any purchases or cash payments in the current business period, no record for this customer will

    appear on the transaction le. Similarly, a customer who did make some purchases or cash pay-

  • Student Solution Exercises 3

    ments could have just moved to this community, and if so, the company may not have had a

    chance to create a master record for this customer.

    Write a complete le-matching accounts receivable program. Use the account number on

    each le as the record key for matching purposes. Assume that each le is a sequential text le with

    records stored in increasing account-number order.

    a) Define class TransactionRecord. Objects of this class contain an account number and

    amount for the transaction. Provide methods to modify and retrieve these values.

    b) Modify class AccountRecord in Fig. 14.6 to include method combine, which takes a

    TransactionRecord object and combines the balance of the AccountRecord object and

    amount value of the TransactionRecord object.

    c) Write a program to create data for testing the program. Use the sample account data in

    Figs. 14.24 and 14.25. Run the program to create the files trans.txt and oldmast.txt,

    to be used by your file-matching program.

    d) Create class FileMatch to perform the file-matching functionality. The class should

    contain methods that read oldmast.txt and trans.txt. When a match occurs (i.e.,

    records with the same account number appear in both the master file and the transac-

    tion file), add the dollar amount in the transaction record to the current balance in the

    master record, and write the "newmast.txt" record. (Assume that purchases are indicat-

    ed by positive amounts in the transaction file and payments by negative amounts.)

    When there is a master record for a particular account, but no corresponding transac-

    tion record, merely write the master record to "newmast.txt". When there is a transac-

    Master le

    Account number Name Balance

    100 Alan Jones 348.17

    300 Mary Smith 27.19

    500 Sam Sharp 0.00

    700 Suzy Green 14.22

    Fig. 14.1 | Sample data for master file.

    Transaction le

    Account number Transaction amount

    100 27.14

    300 62.11

    400 100.56

    900 82.17

    Fig. 14.2 | Sample data for transaction file.

  • 4 Chapter 14 Files and Streams

    tion record, but no corresponding master record, print to a log file the message

    "Unmatched transaction record for account number" (fill in the account number

    from the transaction record). The log file should be a text file named "log.txt".

    ANS:

    1 // Exercise 14.8 Solution: AccountRecord.java

    2 // A class that represents one record of information.

    3

    4 public class AccountRecord

    5 {

    6 private int account;

    7 private String firstName;

    8 private String lastName;

    9 private double balance;

    10

    11 // no-argument constructor calls other constructor with default values

    12 public AccountRecord()

    13 {

    14 this( 0, "", "", 0.0 ); // call four-argument constructor

    15 } // end no-argument AccountRecord constructor

    16

    17 // initialize a record

    18 public AccountRecord( int acct, String first, String last, double bal )

    19 {

    20 setAccount( acct );

    21 setFirstName( first );

    22 setLastName( last );

    23 setBalance( bal );

    24 } // end four-argument AccountRecord constructor

    25

    26 // add a transaction to an account record

    27 public void combine( TransactionRecord transaction )

    28 {

    29 balance = balance + transaction.getAmount();

    30 } // end method combine

    31

    32 // set account number

    33 public void setAccount( int acct )

    34 {

    35 account = acct;

    36 } // end method setAccount

    37

    38 // get account number

    39 public int getAccount()

    40 {

    41 return account;

    42 } // end method getAccount

    43

    44 // set first name

    45 public void setFirstName( String first )

    46 {

    47 firstName = first;

    48 } // end method setFirstName

    49

  • Student Solution Exercises 5

    50 // get first name

    51 public String getFirstName()

    52 {

    53 return firstName;

    54 } // end method getFirstName

    55

    56 // set last name

    57 public void setLastName( String last )

    58 {

    59 lastName = last;

    60 } // end method setLastName

    61

    62 // get last name

    63 public String getLastName()

    64 {

    65 return lastName;

    66 } // end method getLastName

    67

    68 // set balance

    69 public void setBalance( double bal )

    70 {

    71 balance = bal;

    72 } // end method setBalance

    73

    74 // get balance

    75 public double getBalance()

    76 {

    77 return balance;

    78 } // end method getBalance

    79 } // end class AccountRecord

    1 // Exercise 14.8 Solution: TransactionRecord.java

    2 // A class that represents one transaction record.

    3

    4 public class TransactionRecord

    5 {

    6 private int account;

    7 private double amount;

    8

    9 // no-argument constructor calls other constructor with default values

    10 public TransactionRecord()

    11 {

    12 this( 0, 0.0 );

    13 } // end no-argument TransactionRecord

    14

    15 // initialize a record

    16 public TransactionRecord( int acct, double amt )

    17 {

    18 setAccount( acct );

    19 setAmount( amt );

    20 } // end two-argument TransactionRecord

    21

    22 // set account number

    23 public void setAccount( int acct )

  • 6 Chapter 14 Files and Streams

    24 {

    25 account = acct;

    26 } // end method setAccount

    27

    28 // get account number

    29 public int getAccount()

    30 {

    31 return account;

    32 } // end method getAccount

    33

    34 // set amount

    35 public void setAmount( double amt )

    36 {

    37 amount = amt;

    38 } // end method setAmount

    39

    40 // get amount

    41 public double getAmount()

    42 {

    43 return amount;

    44 } // end method getAmount

    45 } // end class TransactionRecord

    1 // Exercise 14.8 Solution: CreateData.java

    2 // Create data to put into an account file and a transactions file.

    3 import java.io.File;

    4 import java.io.FileNotFoundException;

    5 import java.util.Formatter;

    6 import java.util.FormatterClosedException;

    7 import java.util.IllegalFormatException;

    8

    9 public class CreateData

    10 {

    11 public static void main( String args[] )

    12 {

    13 Formatter outOldMaster = null;

    14 Formatter outTransaction = null;

    15 AccountRecord accounts[] = new AccountRecord[ 4 ];

    16 TransactionRecord transactions[] = new TransactionRecord[ 4 ];

    17

    18 // create account records

    19 accounts[ 0 ] = new AccountRecord( 100, "Alan", "Jones", 348.17 );

    20 accounts[ 1 ] = new AccountRecord( 300, "Mary", "Smith", 27.19 );

    21 accounts[ 2 ] = new AccountRecord( 500, "Sam", "Sharp", 0.00 );

    22 accounts[ 3 ] = new AccountRecord( 700, "Suzy", "Green", -14.22 );

    23

    24 // create transactions

    25 transactions[ 0 ] = new TransactionRecord( 100, 27.14 );

    26 transactions[ 1 ] = new TransactionRecord( 300, 62.11 );

    27 transactions[ 2 ] = new TransactionRecord( 400, 100.56 );

    28 transactions[ 3 ] = new TransactionRecord( 900, 82.17 );

    29

  • Student Solution Exercises 7

    30 try

    31 {

    32 // file stream for output file

    33 outOldMaster = new Formatter( "oldmast.txt" );

    34

    35 for ( int i = 0; i < accounts.length; i++ )

    36 {

    37 outOldMaster.format( "%d %s %s %.2f\n",

    38 accounts[ i ].getAccount(), accounts[ i ].getFirstName(),

    39 accounts[ i ].getLastName(), accounts[ i ].getBalance() );

    40 } // end for

    41

    42 // file stream for output file

    43 outTransaction = new Formatter( "trans.txt" );

    44

    45 for ( int i = 0; i < transactions.length; i++ )

    46 {

    47 outTransaction.format( "%d %.2f\n",

    48 transactions[ i ].getAccount(),

    49 transactions[ i ].getAmount() );

    50 } // end for

    51 } // end try

    52 catch ( SecurityException securityException )

    53 {

    54 System.err.println(

    55 "You do not have write access to this file." );

    56 System.exit( 1 );

    57 } // end catch

    58 catch ( FileNotFoundException fileNotFoundException )

    59 {

    60 System.err.println( "Error creating file." );

    61 System.exit( 1 );

    62 } // end catch

    63 catch ( IllegalFormatException formatException )

    64 {

    65 System.err.println( "Error with output." );

    66 System.exit( 1 );

    67 } // end catch

    68 catch ( FormatterClosedException closedException )

    69 {

    70 System.err.println(

    71 "Error writing to file - file has been closed." );

    72 System.exit( 1 );

    73 } // end catch

    74 finally

    75 {

    76 if ( outOldMaster != null )

    77 outOldMaster.close();

    78

    79 if ( outTransaction != null )

    80 outTransaction.close();

    81 } // end finally

    82 } // end main

    83 } // end class CreateData

  • 8 Chapter 14 Files and Streams

    ANS: Contents of oldmast.txt after CreateData.java is executed:

    ANS: Contents of trans.txt after CreateData.java is executed:

    100 Alan Jones 348.17

    300 Mary Smith 27.19

    500 Sam Sharp 0.00

    700 Suzy Green -14.22

    100 27.14

    300 62.11

    400 100.56

    900 82.17

    1 // Exercise 14.8 Solution: FileMatch.java

    2 // Combine an account file with a transactions file into a

    3 // new account file.

    4 import java.io.File;

    5 import java.util.Formatter;

    6 import java.util.FormatterClosedException;

    7 import java.util.IllegalFormatException;

    8 import java.util.NoSuchElementException;

    9 import java.util.Scanner;

    10

    11 public class FileMatch

    12 {

    13 private static Scanner inOldMaster;

    14 private static Scanner inTransaction;

    15 private static Formatter outNewMaster;

    16 private static Formatter logFile;

    17 private static TransactionRecord transaction;

    18 private static AccountRecord account;

    19

    20 public FileMatch()

    21 {

    22 transaction = new TransactionRecord();

    23 account = new AccountRecord();

    24 } // end FileMatch constructor

    25

    26 public void openFiles()

    27 {

    28 try

    29 {

    30 // file streams for input and output files

    31 inOldMaster = new Scanner( new File( "oldmast.txt" ) );

    32 inTransaction = new Scanner( new File( "trans.txt" ) );

    33 outNewMaster = new Formatter( "newmast.txt" );

    34 logFile = new Formatter( "log.txt" );

    35 } // end try

  • Student Solution Exercises 9

    36 catch ( Exception exception )

    37 {

    38 System.err.println( "Error opening the files." );

    39 } // end catch

    40 } // end method openFiles

    41

    42 public void processFiles()

    43 {

    44 int transactionAccountNumber;

    45 int accountNumber;

    46

    47 try // block for reading/writing all records

    48 {

    49 // get a transaction record and its account number

    50 transaction = getTransactionRecord();

    51

    52 // if the transaction is null, we are done

    53 if ( transaction == null )

    54 return;

    55

    56 transactionAccountNumber = transaction.getAccount();

    57

    58 // get an account record and its account number

    59 account = getAccountRecord();

    60

    61 // if the account is null, we are done

    62 if ( account == null )

    63 return;

    64

    65 accountNumber = account.getAccount();

    66

    67 while ( accountNumber != 0 )

    68 {

    69 while ( accountNumber < transactionAccountNumber )

    70 {

    71 // there is no transaction for this account

    72 outNewMaster.format( "%d %s %s %.2f\n",

    73 account.getAccount(), account.getFirstName(),

    74 account.getLastName(), account.getBalance() );

    75

    76 account = getAccountRecord(); // get a new account

    77

    78 if ( account == null )

    79 return;

    80

    81 accountNumber = account.getAccount();

    82 } // end while

    83

    84 // if there is a transaction for this account

    85 if ( accountNumber == transactionAccountNumber )

    86 {

    87 // combine the records

    88 account.combine( transaction );

    89

  • 10 Chapter 14 Files and Streams

    90 // write to the master file

    91 outNewMaster.format( "%d %s %s %.2f\n",

    92 account.getAccount(), account.getFirstName(),

    93 account.getLastName(), account.getBalance() );

    94

    95 // get a new transaction

    96 transaction = getTransactionRecord();

    97

    98 if ( transaction == null )

    99 return;

    100

    101 transactionAccountNumber = transaction.getAccount();

    102

    103 // get a new account

    104 account = getAccountRecord();

    105

    106 if ( account == null )

    107 return;

    108

    109 accountNumber = account.getAccount();

    110 } // end if

    111

    112 while ( transactionAccountNumber < accountNumber )

    113 {

    114 // there is no account for this transaction

    115 logFile.format( "%s %d\n",

    116 "Unmatched transaction record for account number",

    117 transactionAccountNumber );

    118

    119 // get a new transaction

    120 transaction = getTransactionRecord();

    121

    122 if ( transaction == null )

    123 return;

    124

    125 transactionAccountNumber = transaction.getAccount();

    126 } // end while

    127 } // end outer while

    128 } // end try

    129 catch ( FormatterClosedException closedException )

    130 {

    131 System.err.println(

    132 "Error writing to file - file has been closed." );

    133 System.exit( 1 );

    134 } // end catch

    135 catch ( IllegalFormatException formatException )

    136 {

    137 System.err.println( "Error with output." );

    138 System.exit( 1 );

    139 } // end catch

    140 } // end method processFiles

    141

    142 public void closeFiles()

    143 {

  • Student Solution Exercises 11

    144 try // close the files

    145 {

    146 if ( inTransaction != null )

    147 inTransaction.close();

    148

    149 if ( outNewMaster != null )

    150 outNewMaster.close();

    151

    152 if ( inOldMaster != null )

    153 inOldMaster.close();

    154

    155 if ( logFile != null )

    156 logFile.close();

    157 } // end try

    158 catch ( Exception exception )

    159 {

    160 System.err.println( "Error closing the files." );

    161 System.exit( 1 );

    162 } // end catch

    163 } // end method closeFiles

    164

    165 // get a transaction record

    166 private TransactionRecord getTransactionRecord()

    167 {

    168 // try to read the record

    169 try

    170 {

    171 if ( inTransaction.hasNext() )

    172 {

    173 transaction.setAccount( inTransaction.nextInt() );

    174 transaction.setAmount( inTransaction.nextDouble() );

    175

    176 return transaction;

    177 } // end if

    178 else // we have hit end of transaction file

    179 {

    180 // these remaining accounts have

    181 while ( inOldMaster.hasNext() )

    182 {

    183 account.setAccount( inOldMaster.nextInt() );

    184 account.setFirstName( inOldMaster.next() );

    185 account.setLastName( inOldMaster.next() );

    186 account.setBalance( inOldMaster.nextDouble() );

    187

    188 // store in new master

    189 outNewMaster.format( "%d %s %s %.2f\n",

    190 account.getAccount(), account.getFirstName(),

    191 account.getLastName(), account.getBalance() );

    192 } // end while

    193 } // end else

    194 } // end try

    195 catch ( FormatterClosedException closedException )

    196 {

    197 System.err.println(

    198 "Error writing to file - file has been closed." );

    199 System.exit( 1 );

  • 12 Chapter 14 Files and Streams

    200 } // end catch

    201 catch ( IllegalFormatException formatException )

    202 {

    203 System.err.println( "Error with output." );

    204 System.exit( 1 );

    205 } // end catch

    206 catch ( NoSuchElementException elementException )

    207 {

    208 System.err.println( "Invalid input from file." );

    209 } // end catch

    210

    211 // return null - no more records

    212 return null;

    213 } // end method getTransactionRecord

    214

    215 // get an account record

    216 private AccountRecord getAccountRecord()

    217 {

    218 try // try to read an account record

    219 {

    220 if ( inOldMaster.hasNext() )

    221 {

    222 account.setAccount( inOldMaster.nextInt() );

    223 account.setFirstName( inOldMaster.next() );

    224 account.setLastName( inOldMaster.next() );

    225 account.setBalance( inOldMaster.nextDouble() );

    226

    227 return account;

    228 } // end if

    229 else // we have hit end of old master file

    230 {

    231 logFile.format( "%s %d\n",

    232 "Unmatched transaction record for account number",

    233 transaction.getAccount() );

    234

    235 // these records are transactions without accounts

    236 while ( inTransaction.hasNext() )

    237 {

    238 transaction.setAccount( inTransaction.nextInt() );

    239 transaction.setAmount( inTransaction.nextDouble() );

    240 } // end while

    241 } // end else

    242 } // end try

    243 catch ( FormatterClosedException closedException )

    244 {

    245 System.err.println(

    246 "Error writing to file - file has been closed." );

    247 System.exit( 1 );

    248 } // end catch

    249 catch ( IllegalFormatException formatException )

    250 {

    251 System.err.println( "Error with output." );

    252 System.exit( 1 );

    253 } // end catch

    254 catch ( NoSuchElementException elementException )

  • Student Solution Exercises 13

    ANS: Contents of newmast.txt after FileMatchTest is executed.

    ANS: Contents of log.txt after FileMatchTest is executed.

    14.12 (Student Poll) Figure 7.8 contains an array of survey responses that is hard coded into the

    program. Suppose we wish to process survey results that are stored in a file. This exercise requires

    two separate programs. First, create an application that prompts the user for survey responses and

    outputs each response to a file. Use a Formatter to create a file called numbers.txt. Each integer

    should be written using method format. Then modify the program of Fig. 7.8 to read the survey

    responses from numbers.txt. The responses should be read from the file by using a Scanner. Meth-

    od nextInt should be used to input one integer at a time from the file. The program should con-

    tinue to read responses until it reaches the end of file. The results should be output to the text file

    "output.txt".

    255 {

    256 System.err.println( "Invalid input from file." );

    257 } // end catch

    258

    259 return null;

    260 } // end method getAccountRecord

    261 } // end class FileMatch

    1 // Exercise 14.8 Solution: FileMatchTest.java

    2 // Tests FileMatch program.

    3

    4 public class FileMatchTest

    5 {

    6 public static void main( String args[] )

    7 {

    8 FileMatch application = new FileMatch();

    9

    10 application.openFiles();

    11 application.processFiles();

    12 application.closeFiles();

    13 } // end main

    14 } // end class FileMatchTest

    100 Alan Jones 375.31

    300 Mary Smith 89.30

    500 Sam Sharp 0.00

    700 Suzy Green -14.22

    Unmatched transaction record for account number 400

    Unmatched transaction record for account number 900

  • 14 Chapter 14 Files and Streams

    ANS:

    1 // Exercise 14.12 Solution: CreateResults.java

    2 // Create poll results and output them to a file.

    3 import java.io.FileNotFoundException;

    4 import java.util.Formatter;

    5 import java.util.FormatterClosedException;

    6 import java.util.IllegalFormatException;

    7 import java.util.NoSuchElementException;

    8 import java.util.Scanner;

    9

    10 public class CreateResults

    11 {

    12 private int getValue()

    13 {

    14 int result = -1;

    15 Scanner scanner = new Scanner( System.in );

    16

    17 // prompt the user for input

    18 System.out.print(

    19 "Enter integer result (1 - 10), -1 to quit: " );

    20

    21 try

    22 {

    23 result = scanner.nextInt();

    24 } // end try

    25 catch ( NoSuchElementException noSuchElementException )

    26 {

    27 System.err.println( "Error with input." );

    28 System.exit( 1 );

    29 } // end catch

    30

    31 return result;

    32 } // end method getValue

    33

    34 private void outputData()

    35 {

    36 Formatter pollNumbers = null;

    37

    38 try

    39 {

    40 // create the output stream

    41 pollNumbers = new Formatter( "numbers.txt" );

    42

    43 int pollValue = getValue(); // get a number from the user

    44

    45 // test for the sentinel value

    46 while ( pollValue != -1 )

    47 {

    48 // if the number is valid

    49 if ( pollValue > 0 && pollValue < 11 )

    50

    51 // write the value

    52 pollNumbers.format( "%d\n", pollValue );

    53

  • Student Solution Exercises 15

    54 pollValue = getValue(); // get another value

    55 } // end while

    56

    57 pollNumbers.close(); // close the file

    58 } // end try

    59 catch( SecurityException securityException )

    60 {

    61 System.err.println( "Error opening file." );

    62 } // end catch

    63 catch( FileNotFoundException fileNotFoundException )

    64 {

    65 System.err.println( "Output file cannot be found." );

    66 } // end catch

    67 catch( IllegalFormatException illegalFormatException )

    68 {

    69 System.err.println( "Error with the output's format." );

    70 } // end catch

    71 catch( FormatterClosedException formatterClosedException )

    72 {

    73 System.err.println( "File has been closed." );

    74 } // end catch

    75 finally

    76 {

    77 if ( pollNumbers != null )

    78 pollNumbers.close();

    79 } // end finally

    80 } // end method outputData

    81

    82 public static void main( String args[] )

    83 {

    84 CreateResults application = new CreateResults();

    85 application.outputData();

    86 } // end main

    87 } // end class CreateResults

  • 16 Chapter 14 Files and Streams

    ANS: Contents of numbers.txt after CreateResults.java has been executed:

    3

    4

    5

    2

    2

    2

    8

    8

    9

    9

    9

    9

    9

    5

    7

    7

    7

    1 // Exercise 14.12 Solution: StudentPoll.java

    2 // Read poll results from a file and output ratings.

    3 import java.io.File;

    4 import java.io.FileNotFoundException;

    5 import java.util.Formatter;

    6 import java.util.FormatterClosedException;

    7 import java.util.IllegalFormatException;

    8 import java.util.NoSuchElementException;

    9 import java.util.Scanner;

    10

    11 public class StudentPoll

    12 {

    13 public void displayData()

    14 {

    15 int frequency[] = new int[ 11 ];

    16

    17 Formatter writer = null;

    18 Scanner pollNumbers = null;

    19

    20 try

    21 {

    22 pollNumbers = new Scanner(

    23 new File( "numbers.txt" ) );

    24

    25 writer = new Formatter( "output.txt" );

    26

    27 writer.format( "%-12s%-12s\n", "Rating", "Frequency" );

    28

    29 // for each answer, use that value as subscript to

    30 // determine element to increment

    31 while ( pollNumbers.hasNext() )

    32 ++frequency[ pollNumbers.nextInt() ];

    33

  • Student Solution Exercises 17

    34 // append frequencies to String output

    35 for ( int rating = 1; rating < frequency.length; rating++ )

    36 writer.format( "%-12d%-12d\n", rating, frequency[ rating ] );

    37 } // end try

    38 catch ( FileNotFoundException fileNotFoundException )

    39 {

    40 System.err.println( "Error: Files cannot be opened." );

    41 } // end catch

    42 catch ( FormatterClosedException formatterClosedException )

    43 {

    44 System.err.println( "Error: Output file is closed." );

    45 } // end catch

    46 catch ( SecurityException securityException )

    47 {

    48 System.err.println( "Error opening file for writing." );

    49 } // end catch

    50 catch ( IllegalFormatException illegalFormatException )

    51 {

    52 System.err.println( "Error writing data to file." );

    53 } // end catch

    54 catch ( NoSuchElementException noSuchElementException )

    55 {

    56 System.err.println( "Error reading from file." );

    57 } // end catch

    58 catch ( IllegalStateException illegalStateException )

    59 {

    60 System.err.println( "Error: Input file is closed." );

    61 } // end catch

    62 finally

    63 {

    64 if ( writer != null )

    65 writer.close();

    66

    67 if ( pollNumbers != null )

    68 pollNumbers.close();

    69 } // end finally

    70 } // end displayData

    71 } // end class StudentPoll

    1 // Exercise 14.12 Solution: StudentPollTest.java

    2 // Testing the StudentPoll class.

    3

    4 public class StudentPollTest

    5 {

    6 public static void main( String args[] )

    7 {

    8 StudentPoll application = new StudentPoll();

    9 application.displayData();

    10 } // end main

    11 } // end class StudentPollTest

  • 18 Chapter 14 Files and Streams

    ANS: Contents of output.txt after StudentPollTest.java has been executed.

    14.13 Modify Exercise 11.18 to allow the user to save a drawing into a file or load a prior drawing

    from a file using object serialization. Add buttons Load (to read objects from a file) and Save (to

    write objects to a file). Use an ObjectOutputStream to write to the file and an ObjectInputStream

    to read from the file. Write the array of MyShape objects using method writeObject (class Ob-

    jectOutputStream), and read the array using method readObject (ObjectInputStream). Note that

    the object-serialization mechanism can read or write entire arraysit is not necessary to manipulate

    each element of the array of MyShape objects individually. It is simply required that all the shapes be

    Serializable. Because the array of MyShape objects is of length 100 (and is not necessarily filled

    with shapes drawn by the user), you may also want to store the number of shapes drawn to the file.

    For both the Load and Save buttons, use a JFileChooser to allow the user to select the file in which

    the shapes will be stored or from which they will be read. When the user first runs the program, no

    shapes should be displayed on the screen. The user can display shapes by opening a previously saved

    file of shapes or by drawing their own shapes. Once there are shapes on the screen, users can save

    them to a file using the Save button.

    ANS:

    Rating Frequency

    1 0

    2 3

    3 1

    4 1

    5 2

    6 0

    7 3

    8 2

    9 5

    10 0

    1 // Exercise 14.13: MyShape.java

    2 // Declaration of class MyShape.

    3 import java.awt.Color;

    4 import java.awt.Graphics;

    5 import java.io.Serializable;

    6

    7 public abstract class MyShape implements Serializable

    8 {

    9 private int x1; // x coordinate of first endpoint

    10 private int y1; // y coordinate of first endpoint

    11 private int x2; // x coordinate of second endpoint

    12 private int y2; // y coordinate of second endpoint

    13 private Color myColor; // color of this shape

    14

    15 // default constructor initializes values with 0

    16 public MyShape()

    17 {

    18 this( 0, 0, 0, 0, Color.BLACK ); // call constructor to set values

    19 } // end MyShape no-argument constructor

    20

    21 // constructor

  • Student Solution Exercises 19

    22 public MyShape( int x1, int y1, int x2, int y2, Color color )

    23 {

    24 setX1( x1 ); // set x coordinate of first endpoint

    25 setY1( y1 ); // set y coordinate of first endpoint

    26 setX2( x2 ); // set x coordinate of second endpoint

    27 setY2( y2 ); // set y coordinate of second endpoint

    28 setColor( color ); // set the color

    29 } // end MyShape constructor

    30

    31 // set the x-coordinate of the first point

    32 public void setX1( int x1 )

    33 {

    34 this.x1 = ( x1 >= 0 ? x1 : 0 );

    35 } // end method setX1

    36

    37 // get the x-coordinate of the first point

    38 public int getX1()

    39 {

    40 return x1;

    41 } // end method getX1

    42

    43 // set the x-coordinate of the second point

    44 public void setX2( int x2 )

    45 {

    46 this.x2 = ( x2 >= 0 ? x2 : 0 );

    47 } // end method setX2

    48

    49 // get the x-coordinate of the second point

    50 public int getX2()

    51 {

    52 return x2;

    53 } // end method getX2

    54

    55 // set the y-coordinate of the first point

    56 public void setY1( int y1 )

    57 {

    58 this.y1 = ( y1 >= 0 ? y1 : 0 );

    59 } // end method setY1

    60

    61 // get the y-coordinate of the first point

    62 public int getY1()

    63 {

    64 return y1;

    65 } // end method getY1

    66

    67 // set the y-coordinate of the second point

    68 public void setY2( int y2 )

    69 {

    70 this.y2 = ( y2 >= 0 ? y2 : 0 );

    71 } // end method setY2

    72

    73 // get the y-coordinate of the second point

    74 public int getY2()

    75 {

    76 return y2;

    77 } // end method getY2

    78

  • 20 Chapter 14 Files and Streams

    79 // set the color

    80 public void setColor( Color color )

    81 {

    82 myColor = color;

    83 } // end method setColor

    84

    85 // get the color

    86 public Color getColor()

    87 {

    88 return myColor;

    89 } // end method getColor

    90

    91 // abstract draw method

    92 public abstract void draw( Graphics g );

    93 } // end class MyShape

    1 // Exercise 14.13: MyLine.java

    2 // Declaration of class MyLine.

    3 import java.awt.Color;

    4 import java.awt.Graphics;

    5

    6 public class MyLine extends MyShape

    7 {

    8 // call default superclass constructor

    9 public MyLine()

    10 {

    11 super();

    12 } // end MyLine no-argument constructor

    13

    14 // call superclass constructor passing parameters

    15 public MyLine( int x1, int y1, int x2, int y2, Color color )

    16 {

    17 super( x1, y1, x2, y2, color );

    18 } // end MyLine constructor

    19

    20 // draw line in specified color

    21 public void draw( Graphics g )

    22 {

    23 g.setColor( getColor() );

    24 g.drawLine( getX1(), getY1(), getX2(), getY2() );

    25 } // end method draw

    26 } // end class MyLine

    1 // Exercise 14.13: MyBoundedShape.java

    2 // Declaration of class MyBoundedShape.

    3 import java.awt.Color;

    4 import java.awt.Graphics;

    5

    6 public abstract class MyBoundedShape extends MyShape

    7 {

    8 private boolean filled; // whether this shape is filled

    9

  • Student Solution Exercises 21

    10 // call default superclass constructor

    11 public MyBoundedShape()

    12 {

    13 super();

    14 setFilled( false );

    15 } // end MyBoundedShape no-argument constructor

    16

    17 // call superclass constructor passing parameters

    18 public MyBoundedShape( int x1, int y1, int x2, int y2,

    19 Color color, boolean isFilled )

    20 {

    21 super( x1, y1, x2, y2, color );

    22 setFilled( isFilled );

    23 } // end MyBoundedShape constructor

    24

    25 // get upper left x coordinate

    26 public int getUpperLeftX()

    27 {

    28 return Math.min( getX1(), getX2() );

    29 } // end method getUpperLeftX

    30

    31 // get upper left y coordinate

    32 public int getUpperLeftY()

    33 {

    34 return Math.min( getY1(), getY2() );

    35 } // end method getUpperLeftY

    36

    37 // get shape width

    38 public int getWidth()

    39 {

    40 return Math.abs( getX2() - getX1() );

    41 } // end method getWidth

    42

    43 // get shape height

    44 public int getHeight()

    45 {

    46 return Math.abs( getY2() - getY1() );

    47 } // end method getHeight

    48

    49 // determines whether this shape is filled

    50 public boolean isFilled()

    51 {

    52 return filled;

    53 } // end method is filled

    54

    55 // sets whether this shape is filled

    56 public void setFilled( boolean isFilled )

    57 {

    58 filled = isFilled;

    59 } // end method setFilled

    60 } // end class MyBoundedShape

  • 22 Chapter 14 Files and Streams

    1 // Exercise 14.13: MyRect.java

    2 // Declaration of class MyRect.

    3 import java.awt.Color;

    4 import java.awt.Graphics;

    5

    6 public class MyRect extends MyBoundedShape

    7 {

    8 // call default superclass constructor

    9 public MyRect()

    10 {

    11 super();

    12 } // end MyRect no-argument constructor

    13

    14 // call superclass constructor passing parameters

    15 public MyRect( int x1, int y1, int x2, int y2,

    16 Color color, boolean isFilled )

    17 {

    18 super( x1, y1, x2, y2, color, isFilled );

    19 } // end MyRect constructor

    20

    21 // draw rectangle

    22 public void draw( Graphics g )

    23 {

    24 g.setColor( getColor() );

    25

    26 if ( isFilled() )

    27 g.fillRect( getUpperLeftX(), getUpperLeftY(),

    28 getWidth(), getHeight() );

    29 else

    30 g.drawRect( getUpperLeftX(), getUpperLeftY(),

    31 getWidth(), getHeight() );

    32 } // end method draw

    33 } // end class MyRect

    1 // Exercise 14.13: MyOval.java

    2 // Declaration of class MyOval.

    3 import java.awt.Color;

    4 import java.awt.Graphics;

    5

    6 public class MyOval extends MyBoundedShape

    7 {

    8 // call default superclass constructor

    9 public MyOval()

    10 {

    11 super();

    12 } // end MyOval no-argument constructor

    13

    14 // call superclass constructor passing parameters

    15 public MyOval( int x1, int y1, int x2, int y2,

    16 Color color, boolean isFilled )

    17 {

    18 super( x1, y1, x2, y2, color, isFilled );

    19 } // end MyOval constructor

  • Student Solution Exercises 23

    20

    21 // draw oval

    22 public void draw( Graphics g )

    23 {

    24 g.setColor( getColor() );

    25

    26 if ( isFilled() )

    27 g.fillOval( getUpperLeftX(), getUpperLeftY(),

    28 getWidth(), getHeight() );

    29 else

    30 g.drawOval( getUpperLeftX(), getUpperLeftY(),

    31 getWidth(), getHeight() );

    32 } // end method draw

    33 } // end class MyOval

    1 // Exercise 14.13: DrawPanel.java

    2 // JPanel that allows the user to draw shapes with the mouse.

    3 import java.awt.Color;

    4 import java.awt.Graphics;

    5 import java.awt.event.MouseAdapter;

    6 import java.awt.event.MouseEvent;

    7 import java.awt.event.MouseMotionListener;

    8 import java.io.EOFException;

    9 import java.io.File;

    10 import java.io.FileInputStream;

    11 import java.io.FileOutputStream;

    12 import java.io.IOException;

    13 import java.io.ObjectInputStream;

    14 import java.io.ObjectOutputStream;

    15 import javax.swing.JFileChooser;

    16 import javax.swing.JLabel;

    17 import javax.swing.JOptionPane;

    18 import javax.swing.JPanel;

    19

    20 public class DrawPanel extends JPanel

    21 {

    22 private MyShape shapes[]; // array containing all the shapes

    23 private int shapeCount; // statistic on the number of each shape

    24

    25 private int shapeType; // the type of shape to draw

    26 private MyShape currentShape; // the current shape being drawn

    27 private Color currentColor; // the color of the shape

    28 private boolean filledShape; // whether this shape is filled

    29

    30 private JLabel statusLabel; // label displaying mouse coordinates

    31

    32 // constructor

    33 public DrawPanel( JLabel status )

    34 {

    35 shapes = new MyShape[ 100 ]; // create the array

    36 shapeCount = 0; // initially we have no shapes

    37

    38 setShapeType( 0 ); // initially draw lines

    39 setDrawingColor( Color.BLACK ); // start drawing with black

  • 24 Chapter 14 Files and Streams

    40 setFilledShape( false );// not filled by default

    41 currentShape = null; // not drawing anything initially

    42

    43 setBackground( Color.WHITE ); // set a white background

    44

    45 // add the mouse listeners

    46 MouseHandler mouseHandler = new MouseHandler();

    47 addMouseListener( mouseHandler );

    48 addMouseMotionListener( mouseHandler );

    49

    50 // set the status label for displaying mouse coordinates

    51 statusLabel = status;

    52 } // end DrawPanel constructor

    53

    54 // draw shapes using polymorphism

    55 public void paintComponent( Graphics g )

    56 {

    57 super.paintComponent( g );

    58

    59 for ( int i = 0; i < shapeCount; i++ )

    60 shapes[ i ].draw( g );

    61

    62 if ( currentShape != null )

    63 currentShape.draw( g );

    64 } // end method paintComponent

    65

    66 // sets the type of shape to draw

    67 public void setShapeType( int shapeType )

    68 {

    69 if ( shapeType < 0 || shapeType > 2 )

    70 shapeType = 0;

    71

    72 this.shapeType = shapeType;

    73 } // end method setShapeType

    74

    75 // sets the drawing color

    76 public void setDrawingColor( Color c )

    77 {

    78 currentColor = c;

    79 } // end method setDrawingColor

    80

    81 // clears the last shape drawn

    82 public void clearLastShape()

    83 {

    84 if ( shapeCount > 0 )

    85 {

    86 shapeCount--;

    87 repaint();

    88 } // end if

    89 } // end method clearLastShape

    90

    91 // clears all drawings on this panel

    92 public void clearDrawing()

    93 {

    94 shapeCount = 0;

  • Student Solution Exercises 25

    95 repaint();

    96 } // end method clearDrawing

    97

    98 // sets whether to draw a filled shape

    99 public void setFilledShape( boolean isFilled )

    100 {

    101 filledShape = isFilled;

    102 } // end method setFilledShape

    103

    104 // load saved drawing

    105 public void loadDrawing()

    106 {

    107 ObjectInputStream input = null;

    108

    109 try // user selects file, shapes are input

    110 {

    111 // use JFileChooser to select file

    112 JFileChooser fileChooser = new JFileChooser();

    113 fileChooser.setFileSelectionMode(

    114 JFileChooser.FILES_ONLY );

    115

    116 int result = fileChooser.showOpenDialog(

    117 DrawPanel.this );

    118

    119 // if user clicked Cancel button on dialog, return

    120 if ( result == JFileChooser.CANCEL_OPTION )

    121 return;

    122

    123 // get selected file

    124 File fileName = fileChooser.getSelectedFile();

    125

    126 // display error if invalid

    127 if ( ( fileName == null ) ||

    128 ( fileName.getName().equals( "" ) ) )

    129 {

    130 JOptionPane.showMessageDialog( DrawPanel.this,

    131 "Invalid File Name", "Invalid File Name",

    132 JOptionPane.ERROR_MESSAGE );

    133 return;

    134 } // end if

    135

    136 // open file for input

    137 input = new ObjectInputStream(

    138 new FileInputStream( fileName ) );

    139

    140 // read in number of shapes using deserialization

    141 shapeCount = ( Integer ) input.readObject();

    142

    143 // read in shapes using deserialization

    144 // set shapes to be displayed on drawPanel

    145 shapes = ( MyShape [] ) input.readObject();

    146

    147 repaint(); // redraw shapes

    148 } // end try

    149 catch ( EOFException eofException )

  • 26 Chapter 14 Files and Streams

    150 {

    151 JOptionPane.showMessageDialog( DrawPanel.this,

    152 "No more records in file.", "End of File",

    153 JOptionPane.ERROR_MESSAGE );

    154 } // end catch

    155 catch ( ClassNotFoundException classNotFoundException )

    156 {

    157 JOptionPane.showMessageDialog( DrawPanel.this,

    158 "Unable to create object.", "Class Not Found",

    159 JOptionPane.ERROR_MESSAGE );

    160 } // end catch

    161 catch ( IOException ioException )

    162 {

    163 JOptionPane.showMessageDialog( DrawPanel.this,

    164 "Error opening file.", "Error",

    165 JOptionPane.ERROR_MESSAGE );

    166 } // end catch

    167 finally

    168 {

    169 try

    170 {

    171 if ( input != null )

    172 input.close(); // close file and stream

    173 } // end try

    174 catch ( IOException ioException )

    175 {

    176 JOptionPane.showMessageDialog( DrawPanel.this,

    177 "Error closing file.", "Error",

    178 JOptionPane.ERROR_MESSAGE );

    179 } // end catch

    180 } // end finally

    181 } // end method loadDrawing

    182

    183 // save drawing as serialized objects

    184 public void saveDrawing()

    185 {

    186 ObjectOutputStream output = null;

    187

    188 try

    189 {

    190 // use JFileChooser to select file

    191 JFileChooser fileChooser = new JFileChooser();

    192 fileChooser.setFileSelectionMode(

    193 JFileChooser.FILES_ONLY );

    194

    195 int result = fileChooser.showSaveDialog(

    196 DrawPanel.this );

    197

    198 // if user clicked Cancel button on dialog, return

    199 if ( result == JFileChooser.CANCEL_OPTION )

    200 return;

    201

    202 // get selected file

    203 File fileName = fileChooser.getSelectedFile();

    204

  • Student Solution Exercises 27

    205 // display error if invalid

    206 if ( ( fileName == null ) ||

    207 ( fileName.getName().equals( "" ) ) )

    208 {

    209 JOptionPane.showMessageDialog( DrawPanel.this,

    210 "Invalid File Name", "Invalid File Name",

    211 JOptionPane.ERROR_MESSAGE );

    212 return;

    213 } // end if

    214

    215 // open file for output

    216 output = new ObjectOutputStream(

    217 new FileOutputStream( fileName ) );

    218

    219 // write number of shapes to file

    220 output.writeObject( shapeCount );

    221

    222 // write shapes to file using serialization

    223 output.writeObject( shapes );

    224 } // end try

    225 catch ( IOException ioException )

    226 {

    227 JOptionPane.showMessageDialog( DrawPanel.this,

    228 "Error Opening File", "Error.",

    229 JOptionPane.ERROR_MESSAGE );

    230 } // end catch

    231 finally

    232 {

    233 try

    234 {

    235 if ( output != null )

    236 output.close(); // close file and stream

    237 } // end try

    238 catch ( IOException ioException )

    239 {

    240 JOptionPane.showMessageDialog( DrawPanel.this,

    241 "Error closing file.", "Error",

    242 JOptionPane.ERROR_MESSAGE );

    243 } // end catch

    244 } // end finally

    245 } // end method saveDrawing

    246

    247 // Handles mouse events for this JPanel

    248 private class MouseHandler extends MouseAdapter

    249 implements MouseMotionListener

    250 {

    251 // creates and sets the initial position for the new shape

    252 public void mousePressed( MouseEvent e )

    253 {

    254 if ( currentShape != null )

    255 return;

    256

    257 // create the appropriate shape based on shapeType

    258 switch ( shapeType )

    259 {

  • 28 Chapter 14 Files and Streams

    260 case 0:

    261 currentShape = new MyLine( e.getX(), e.getY(),

    262 e.getX(), e.getY(), currentColor );

    263 break;

    264 case 1:

    265 currentShape = new MyOval( e.getX(), e.getY(),

    266 e.getX(), e.getY(), currentColor, filledShape );

    267 break;

    268 case 2:

    269 currentShape = new MyRect( e.getX(), e.getY(),

    270 e.getX(), e.getY(), currentColor, filledShape );

    271 break;

    272 } // end switch

    273 } // end method mousePressed

    274

    275 // fixes the current shape onto the panel

    276 public void mouseReleased( MouseEvent e )

    277 {

    278 if ( currentShape == null )

    279 return;

    280

    281 // set the second point on the shape

    282 currentShape.setX2( e.getX() );

    283 currentShape.setY2( e.getY() );

    284

    285 // only set the shape if there is room in the array

    286 if ( shapeCount < shapes.length )

    287 {

    288 shapes[ shapeCount ] = currentShape;

    289 shapeCount++;

    290 } // end if

    291

    292 currentShape = null; // clear the temporary drawing shape

    293 repaint();

    294 } // end method mouseReleased

    295

    296 // update the shape to the current mouse position while dragging

    297 public void mouseDragged( MouseEvent e )

    298 {

    299 if ( currentShape != null )

    300 {

    301 currentShape.setX2( e.getX() );

    302 currentShape.setY2( e.getY() );

    303 repaint();

    304 } // end if

    305

    306 mouseMoved( e ); // update status bar

    307 } // end method mouseDragged

    308

    309 // updates the status bar to show the current mouse coordinates

    310 public void mouseMoved( MouseEvent e )

    311 {

    312 statusLabel.setText(

    313 String.format( "(%d,%d)", e.getX(), e.getY() ) );

    314 } // end method mouseMoved

  • Student Solution Exercises 29

    315 } // end class MouseHandler

    316 } // end class DrawPanel

    1 // Exercise 14.13: DrawFrame.java

    2 // Program that creates a panel for the user to draw shapes.

    3 // Allows the user to choose the shape and color.

    4 import java.awt.BorderLayout;

    5 import java.awt.Color;

    6 import java.awt.FlowLayout;

    7 import java.awt.event.ActionEvent;

    8 import java.awt.event.ActionListener;

    9 import java.awt.event.ItemEvent;

    10 import java.awt.event.ItemListener;

    11 import javax.swing.JButton;

    12 import javax.swing.JCheckBox;

    13 import javax.swing.JComboBox;

    14 import javax.swing.JFrame;

    15 import javax.swing.JLabel;

    16 import javax.swing.JPanel;

    17

    18 public class DrawFrame extends JFrame

    19 implements ItemListener, ActionListener

    20 {

    21 // Array of possible colors

    22 private Color colors[] = { Color.BLACK, Color.BLUE, Color.CYAN,

    23 Color.DARK_GRAY, Color.GRAY, Color.GREEN, Color.LIGHT_GRAY,

    24 Color.MAGENTA, Color.ORANGE, Color.PINK, Color.RED, Color.WHITE,

    25 Color.YELLOW };

    26

    27 // Array of names corresponding to the possible colors

    28 private String colorNames[] = { "Black", "Blue", "Cyan", "Dark Gray",

    29 "Gray", "Green", "Light Gray", "Magenta", "Orange", "Pink", "Red",

    30 "White", "Yellow" };

    31

    32 // Array of possible shapes

    33 private String shapes[] = { "Line", "Oval", "Rectangle" };

    34

    35 private DrawPanel drawPanel; // panel that handles the drawing

    36

    37 private JButton loadButton; // button to load saved drawing

    38 private JButton saveButton; // button to save drawing to file

    39 private JButton undoButton; // button to undo the last shape drawn

    40 private JButton clearButton; // button to clear all shapes

    41 private JComboBox colorChoices; // combo box for selecting the color

    42 private JComboBox shapeChoices; // combo box for selecting shapes

    43 private JCheckBox filledCheckBox; // check box to toggle filled shapes

    44

    45 // constructor

    46 public DrawFrame()

    47 {

    48 super( "Java Drawings" );

    49

    50 // create a panel to store the components at the top of the frame

    51 JPanel topPanel = new JPanel( new FlowLayout() );

  • 30 Chapter 14 Files and Streams

    52

    53 // create a button for loading a saved drawing

    54 loadButton = new JButton( "Load" );

    55 loadButton.addActionListener( this );

    56 topPanel.add( loadButton );

    57

    58 // create a button for saving drawing

    59 saveButton = new JButton( "Save" );

    60 saveButton.addActionListener( this );

    61 topPanel.add( saveButton );

    62

    63 // create a button for clearing the last drawing

    64 undoButton = new JButton( "Undo" );

    65 undoButton.addActionListener( this );

    66 topPanel.add( undoButton );

    67

    68 // create a button for clearing all drawings

    69 clearButton = new JButton( "Clear" );

    70 clearButton.addActionListener( this );

    71 topPanel.add( clearButton );

    72

    73 // create a combo-box for choosing colors

    74 colorChoices = new JComboBox( colorNames );

    75 colorChoices.addItemListener( this );

    76 topPanel.add( colorChoices );

    77

    78 // create a combo-box for choosing shapes

    79 shapeChoices = new JComboBox( shapes );

    80 shapeChoices.addItemListener( this );

    81 topPanel.add( shapeChoices );

    82

    83 // create a check-box to determine whether the shape is filled

    84 filledCheckBox = new JCheckBox( "Filled" );

    85 filledCheckBox.addItemListener( this );

    86 topPanel.add( filledCheckBox );

    87

    88 // add the top panel to the frame

    89 add( topPanel, BorderLayout.NORTH );

    90

    91 // create a label for the status bar

    92 JLabel statusLabel = new JLabel( "(0,0)" );

    93

    94 // add the status bar at the bottom

    95 add( statusLabel, BorderLayout.SOUTH );

    96

    97 // create the DrawPanel with its status bar label

    98 drawPanel = new DrawPanel( statusLabel );

    99

    100 add( drawPanel ); // add the drawing area to the center

    101 } // end DrawFrame constructor

    102

    103 // handle selections made to a combo box of check box

    104 public void itemStateChanged( ItemEvent e )

    105 {

    106 if ( e.getSource() == shapeChoices ) // choosing a shape

  • Student Solution Exercises 31

    107 drawPanel.setShapeType( shapeChoices.getSelectedIndex() );

    108 else if (e.getSource() == colorChoices ) // choosing a color

    109 drawPanel.setDrawingColor(

    110 colors[ colorChoices.getSelectedIndex() ] );

    111 else if ( e.getSource() == filledCheckBox ) // filled/unfilled

    112 drawPanel.setFilledShape( filledCheckBox.isSelected() );

    113 } // end method itemStateChanged

    114

    115 // handle button clicks

    116 public void actionPerformed( ActionEvent e )

    117 {

    118 if ( e.getSource() == loadButton )

    119 drawPanel.loadDrawing();

    120 else if ( e.getSource() == saveButton )

    121 drawPanel.saveDrawing();

    122 else if ( e.getSource() == undoButton )

    123 drawPanel.clearLastShape();

    124 else if ( e.getSource() == clearButton )

    125 drawPanel.clearDrawing();

    126 } // end method actionPerformed

    127 } // end class DrawFrame

    1 // Exercise 14.14: TestDraw.java

    2 // Test application to display a DrawFrame

    3 import javax.swing.JFrame;

    4

    5 public class TestDraw

    6 {

    7 public static void main( String args[] )

    8 {

    9 DrawFrame application = new DrawFrame();

    10 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

    11 application.setSize( 600, 500 );

    12 application.setVisible( true );

    13 } // end main

    14 } // end class TestDraw

  • 32 Chapter 14 Files and Streams

  • Student Solution Exercises 33

  • 34 Chapter 14 Files and Streams

    Deitel: 2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.