27
Examples for Project 2 • From Deital and Deital, Java: How to Program, Third Edition • Reusable and flexible UI • Data Records with Sequential and Random Access Files

Examples for Project 2 From Deital and Deital, Java: How to Program, Third Edition Reusable and flexible UI Data Records with Sequential and Random Access

Embed Size (px)

Citation preview

Page 1: Examples for Project 2 From Deital and Deital, Java: How to Program, Third Edition Reusable and flexible UI Data Records with Sequential and Random Access

Examples for Project 2

• From Deital and Deital, Java: How to Program, Third Edition

• Reusable and flexible UI

• Data Records with Sequential and Random Access Files

Page 2: Examples for Project 2 From Deital and Deital, Java: How to Program, Third Edition Reusable and flexible UI Data Records with Sequential and Random Access

// Fig. 17.4: BankUI.java// A reusable GUI for the examples in this chapter.package com.deitel.jhtp3.ch17;import java.awt.*;import javax.swing.*;//Swing Componentspublic class BankUI extends JPanel { protected final static String names[] = { "Account number", "First name", "Last name", "Balance", "Transaction Amount" };//Arrays of UI Components that are customizable protected JLabel labels[]; protected JTextField fields[]; protected JButton doTask, doTask2; protected JPanel innerPanelCenter, innerPanelSouth; protected int size = 4; public static final int ACCOUNT = 0, FIRST = 1, LAST = 2, BALANCE = 3, TRANSACTION = 4;

public BankUI() { this( 4 ); }

Page 3: Examples for Project 2 From Deital and Deital, Java: How to Program, Third Edition Reusable and flexible UI Data Records with Sequential and Random Access

public BankUI( int mySize ) { size = mySize; labels = new JLabel[ size ]; fields = new JTextField[ size ];

for ( int i = 0; i < labels.length; i++ ) labels[ i ] = new JLabel( names[ i ] ); for ( int i = 0; i < fields.length; i++ ) fields[ i ] = new JTextField();

innerPanelCenter = new JPanel(); innerPanelCenter.setLayout( new GridLayout( size, 2 ) );

for ( int i = 0; i < size; i++ ) { innerPanelCenter.add( labels[ i ] ); innerPanelCenter.add( fields[ i ] ); }

//Constructor ContinueddoTask = new JButton(); doTask2 = new JButton(); innerPanelSouth = new JPanel(); innerPanelSouth.add( doTask2 ); innerPanelSouth.add( doTask );

setLayout( new BorderLayout() ); add( innerPanelCenter, BorderLayout.CENTER ); add( innerPanelSouth, BorderLayout.SOUTH ); validate(); }

Page 4: Examples for Project 2 From Deital and Deital, Java: How to Program, Third Edition Reusable and flexible UI Data Records with Sequential and Random Access

//Utility methods public JButton getDoTask() { return doTask; }

public JButton getDoTask2() { return doTask2; }

public JTextField[] getFields() { return fields; }

public void clearFields() { for ( int i = 0; i < size; i++ ) fields[ i ].setText( "" ); }

public void setFieldValues( String s[] ) throws IllegalArgumentException { if ( s.length != size ) throw new IllegalArgumentException( "There must be " + size + " Strings in the array" );

for ( int i = 0; i < size; i++ ) fields[ i ].setText( s[ i ] ); }

public String[] getFieldValues() { String values[] = new String[ size ];

for ( int i = 0; i < size; i++ ) values[ i ] = fields[ i ].getText();

return values; }}

Page 5: Examples for Project 2 From Deital and Deital, Java: How to Program, Third Edition Reusable and flexible UI Data Records with Sequential and Random Access

// Fig. 17.4: BankAccountRecord.java// A class that represents one record of information.package com.deitel.jhtp3.ch17;import java.io.Serializable;

public class BankAccountRecord implements Serializable { private int account; private String firstName; private String lastName; private double balance; public BankAccountRecord() { this( 0, "", "", 0.0 ); } public BankAccountRecord( int acct, String first, String last, double bal ) { setAccount( acct ); setFirstName( first ); setLastName( last ); setBalance( bal ); }

Page 6: Examples for Project 2 From Deital and Deital, Java: How to Program, Third Edition Reusable and flexible UI Data Records with Sequential and Random Access

public void setAccount( int acct ) { account = acct; } public int getAccount() { return account; } public void setFirstName( String first ) { firstName = first; } public String getFirstName() { return firstName; } public void setLastName( String last ) { lastName = last; } public String getLastName() { return lastName; } public void setBalance( double bal ) { balance = bal; } public double getBalance() { return balance; }}

Page 7: Examples for Project 2 From Deital and Deital, Java: How to Program, Third Edition Reusable and flexible UI Data Records with Sequential and Random Access

// Fig. 17.4: CreateSequentialFile.java// Demonstrating object output with class ObjectOutputStream.// The objects are written sequentially to a file.import java.io.*;import java.awt.*;import java.awt.event.*;import javax.swing.*;import com.deitel.jhtp3.ch17.BankUI;import com.deitel.jhtp3.ch17.BankAccountRecord;

public class CreateSequentialFile extends JFrame { private ObjectOutputStream output; private BankUI userInterface; private JButton enter, open;//application specific code defined in this class

Page 8: Examples for Project 2 From Deital and Deital, Java: How to Program, Third Edition Reusable and flexible UI Data Records with Sequential and Random Access

public CreateSequentialFile() { super( "Creating a Sequential File of Objects" );//returns container that is GUI component attachment point getContentPane().setLayout( new BorderLayout() ); userInterface = new BankUI();//get a button from BankUI() and customize it enter = userInterface.getDoTask(); enter.setText( "Enter" ); enter.setEnabled( false ); // disable button to start//AL is anonymous class enter.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { addRecord(); } } );

Page 9: Examples for Project 2 From Deital and Deital, Java: How to Program, Third Edition Reusable and flexible UI Data Records with Sequential and Random Access

addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) {//output is object output stream if ( output != null ) { addRecord(); closeFile(); } else System.exit( 0 ); } } ); open = userInterface.getDoTask2();

open.setText( "Save As" ); open.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { openFile(); } } );

Page 10: Examples for Project 2 From Deital and Deital, Java: How to Program, Third Edition Reusable and flexible UI Data Records with Sequential and Random Access

getContentPane().add( userInterface, BorderLayout.CENTER );//add ui to GUI component and make visible setSize( 300, 200 ); show(); }

private void openFile() {//simple way to choose file--Networkable? JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY ); int result = fileChooser.showSaveDialog( this );

// user clicked Cancel button on dialog if ( result == JFileChooser.CANCEL_OPTION ) return;

File fileName = fileChooser.getSelectedFile();

Page 11: Examples for Project 2 From Deital and Deital, Java: How to Program, Third Edition Reusable and flexible UI Data Records with Sequential and Random Access

if ( fileName == null || fileName.getName().equals( "" ) ) JOptionPane.showMessageDialog( this, "Invalid File Name", "Invalid File Name", JOptionPane.ERROR_MESSAGE ); else { // Open the file try { output = new ObjectOutputStream( new FileOutputStream( fileName ) ); open.setEnabled( false ); enter.setEnabled( true ); } catch ( IOException e ) { JOptionPane.showMessageDialog( this, "Error Opening File", "Error", JOptionPane.ERROR_MESSAGE ); } } }

Page 12: Examples for Project 2 From Deital and Deital, Java: How to Program, Third Edition Reusable and flexible UI Data Records with Sequential and Random Access

private void closeFile() { try { output.close(); System.exit( 0 ); } catch( IOException ex ) { JOptionPane.showMessageDialog( this, "Error closing file", "Error", JOptionPane.ERROR_MESSAGE ); System.exit( 1 ); } }

Page 13: Examples for Project 2 From Deital and Deital, Java: How to Program, Third Edition Reusable and flexible UI Data Records with Sequential and Random Access

public void addRecord() {//response to action event int accountNumber = 0; BankAccountRecord record; String fieldValues[] = userInterface.getFieldValues(); // If the account field value is not empty if ( ! fieldValues[ 0 ].equals( "" ) ) { // output the values to the file try { accountNumber = Integer.parseInt( fieldValues[ 0 ] );

if ( accountNumber > 0 ) { record = new BankAccountRecord( accountNumber, fieldValues[ 1 ], fieldValues[ 2 ], Double.parseDouble( fieldValues[ 3 ] ) ); output.writeObject( record ); output.flush(); }

Page 14: Examples for Project 2 From Deital and Deital, Java: How to Program, Third Edition Reusable and flexible UI Data Records with Sequential and Random Access

// clear the TextFields userInterface.clearFields(); } catch ( NumberFormatException nfe ) { JOptionPane.showMessageDialog( this, "Bad account number or balance", "Invalid Number Format", JOptionPane.ERROR_MESSAGE ); } catch ( IOException io ) { closeFile(); } } }

public static void main( String args[] ) { new CreateSequentialFile(); }}

Page 15: Examples for Project 2 From Deital and Deital, Java: How to Program, Third Edition Reusable and flexible UI Data Records with Sequential and Random Access

// Fig. 17.6: ReadSequentialFile.java// This program reads a file of objects sequentially// and displays each record....public class ReadSequentialFile extends JFrame { private ObjectInputStream input; private BankUI userInterface; private JButton nextRecord, open; // Constructor -- initialize the Frame public ReadSequentialFile() { super( "Reading a Sequential File of Objects" ); getContentPane().setLayout( new BorderLayout() ); userInterface = new BankUI(); nextRecord = userInterface.getDoTask(); nextRecord.setText( "Next Record" ); nextRecord.setEnabled( false ); nextRecord.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { readRecord(); } } );

Page 16: Examples for Project 2 From Deital and Deital, Java: How to Program, Third Edition Reusable and flexible UI Data Records with Sequential and Random Access

public void readRecord() { BankAccountRecord record;

// input the values from the file try { record = ( BankAccountRecord ) input.readObject(); String values[] = { String.valueOf( record.getAccount() ), record.getFirstName(), record.getLastName(), String.valueOf( record.getBalance() ) }; userInterface.setFieldValues( values ); } catch ( EOFException eofex ) { ... } catch ( ClassNotFoundException cnfex ) { ... } catch ( IOException ioex ) {

...} }

Page 17: Examples for Project 2 From Deital and Deital, Java: How to Program, Third Edition Reusable and flexible UI Data Records with Sequential and Random Access

// Fig. 17.7: CreditInquiry.java// This program reads a file sequentially and displays the// contents in a text area based on the type of account the// user requests (credit balance, debit balance or// zero balance)....public class CreditInquiry extends JFrame { private JTextArea recordDisplay; private JButton open, done, credit, debit, zero; private JPanel buttonPanel; private ObjectInputStream input; private FileInputStream fileInput; private File fileName; private String accountType; public CreditInquiry() { super( "Credit Inquiry Program" );

Container c = getContentPane(); c.setLayout( new BorderLayout() ); buttonPanel = new JPanel(); ...

Page 18: Examples for Project 2 From Deital and Deital, Java: How to Program, Third Edition Reusable and flexible UI Data Records with Sequential and Random Access

credit = new JButton( "Credit balances" ); credit.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { accountType = e.getActionCommand(); readRecords(); } } ); buttonPanel.add( credit );

debit = new JButton( "Debit balances" ); debit.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { accountType = e.getActionCommand(); readRecords(); } } ); buttonPanel.add( debit );

Page 19: Examples for Project 2 From Deital and Deital, Java: How to Program, Third Edition Reusable and flexible UI Data Records with Sequential and Random Access

private void readRecords() { BankAccountRecord record; DecimalFormat twoDigits = new DecimalFormat( "0.00" ); openFile( false );

try { recordDisplay.setText( "The accounts are:\n" );

// input the values from the file while ( true ) { record = ( BankAccountRecord ) input.readObject();

if ( shouldDisplay( record.getBalance() ) ) recordDisplay.append( record.getAccount() + "\t" + record.getFirstName() + "\t" + record.getLastName() + "\t" + twoDigits.format( record.getBalance() ) + "\n" ); } }...

Page 20: Examples for Project 2 From Deital and Deital, Java: How to Program, Third Edition Reusable and flexible UI Data Records with Sequential and Random Access

private boolean shouldDisplay( double balance ) { if ( accountType.equals( "Credit balances" ) && balance < 0 ) return true; else if ( accountType.equals( "Debit balances" ) && balance > 0 ) return true; else if ( accountType.equals( "Zero balances" ) && balance == 0 ) return true;

return false; }

Page 21: Examples for Project 2 From Deital and Deital, Java: How to Program, Third Edition Reusable and flexible UI Data Records with Sequential and Random Access

// Fig. 17.10: Record.java// Record class for the RandomAccessFile programs.package com.deitel.jhtp3.ch17;import java.io.*;import com.deitel.jhtp3.ch17.BankAccountRecord;

public class Record extends BankAccountRecord { public Record() { this( 0, "", "", 0.0 ); }

public Record( int acct, String first, String last, double bal ) { super( acct, first, last, bal ); }

Page 22: Examples for Project 2 From Deital and Deital, Java: How to Program, Third Edition Reusable and flexible UI Data Records with Sequential and Random Access

// Read a record from the specified RandomAccessFile public void read( RandomAccessFile file ) throws IOException { setAccount( file.readInt() ); setFirstName( padName( file ) ); setLastName( padName( file ) ); setBalance( file.readDouble() ); }//have to pad to get constant size records private String padName( RandomAccessFile f ) throws IOException { char name[] = new char[ 15 ], temp;

for ( int i = 0; i < name.length; i++ ) { temp = f.readChar(); name[ i ] = temp; } //nulls displayed as rectangles, replace return new String( name ).replace( '\0', ' ' ); }

Page 23: Examples for Project 2 From Deital and Deital, Java: How to Program, Third Edition Reusable and flexible UI Data Records with Sequential and Random Access

// Write a record to the specified RandomAccessFile public void write( RandomAccessFile file ) throws IOException { file.writeInt( getAccount() ); writeName( file, getFirstName() ); writeName( file, getLastName() ); file.writeDouble( getBalance() ); } private void writeName( RandomAccessFile f, String name ) throws IOException { StringBuffer buf = null; if ( name != null ) buf = new StringBuffer( name ); else buf = new StringBuffer( 15 ); buf.setLength( 15 ); f.writeChars( buf.toString() ); } // NOTE: This method contains a hard coded value for the // size of a record of information. public static int size() { return 72; }}

Page 24: Examples for Project 2 From Deital and Deital, Java: How to Program, Third Edition Reusable and flexible UI Data Records with Sequential and Random Access

// Fig. 17.12: WriteRandomFile.java// This program uses TextFields to get information from the// user at the keyboard and writes the information to a// random-access file.import com.deitel.jhtp3.ch17.*;import javax.swing.*;import java.io.*;import java.awt.event.*;import java.awt.*;

public class WriteRandomFile extends JFrame { private RandomAccessFile output; private BankUI userInterface; private JButton enter, open;

Page 25: Examples for Project 2 From Deital and Deital, Java: How to Program, Third Edition Reusable and flexible UI Data Records with Sequential and Random Access

// Constructor -- intialize the Frame public WriteRandomFile() { super( "Write to random access file" );

userInterface = new BankUI(); enter = userInterface.getDoTask(); enter.setText( "Enter" ); enter.setEnabled( false ); enter.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { addRecord(); } } );

Page 26: Examples for Project 2 From Deital and Deital, Java: How to Program, Third Edition Reusable and flexible UI Data Records with Sequential and Random Access

public void addRecord() { int accountNumber = 0; String fields[] = userInterface.getFieldValues(); Record record = new Record(); if ( !fields[ BankUI.ACCOUNT ].equals( "" ) ) { // output the values to the file try { accountNumber = Integer.parseInt( fields[ BankUI.ACCOUNT ] );

if ( accountNumber > 0 && accountNumber <= 100 ) { record.setAccount( accountNumber ); record.setFirstName( fields[ BankUI.FIRST ] ); record.setLastName( fields[ BankUI.LAST ] ); record.setBalance( Double.parseDouble( fields[ BankUI.BALANCE ] ) );

output.seek( ( accountNumber - 1 ) * Record.size() ); record.write( output ); }

Page 27: Examples for Project 2 From Deital and Deital, Java: How to Program, Third Edition Reusable and flexible UI Data Records with Sequential and Random Access

userInterface.clearFields(); // clear TextFields } // Create a WriteRandomFile object and start the program public static void main( String args[] ) { new WriteRandomFile(); }}