exception handling.doc

Upload: mad-madhavi

Post on 04-Apr-2018

225 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/29/2019 Exception Handling.doc

    1/86

    - 1 - Dr. Yaos CS 214 Class Notes #2

    Exception HandlingIn Java, the parent class dealing with errors and exceptions is Throwable, which has two majorsubclasses: Exception and Error. The Error class defines the internal system errors; whereas

    the Exception class defines the errors caused by the program. In general, the exception handling

    is to account for and manage the possible run-time errors which may be raised by the program.

    For each block of statements that may raise an exception, an exception handling routine shouldbe coded. The basic syntax is:

    try

    {

    ........statements that may throw exceptions....

    } // try

    catch(Exception-type1 identifier)

    {

    ........exception handling statements......

    } // catch

    catch (Exception-type2 identifier)

    {

    ........exception handling statements......

    }// catch

    The primary operations involved in handling exceptions include:

    1. Declare an exception -- using the key word throws; for example,public static void main(String []x) throws IOException

    1. Throw an exception -- using the operatorthrow; for example,throw new Exception(......);

    1. Catch and handle an exception -- using the try and catch block or blocks.

    try { .........}catch(Exception1........)

    { ......}

    catch(Exception2.......){......}

    The Exception class (java.lang.Throwable) provides a set of methods to assist in the exception

    handling. Listed below are some of them, followed by a program example.Method: public String getMessage()

    Description: Returns the detailed error or exception message.

    Method: public String toString()

    Exception: Returns a brief description of the exception

  • 7/29/2019 Exception Handling.doc

    2/86

    - 2 - Dr. Yaos CS 214 Class Notes #2

    Catch1.java

    // Handling exceptionimport java.io.*;

    public class Catch1

    {

    public static void main(String []x) throws IOException{

    int k = 12;int n = 0;

    try

    {

    // try to divide a number by 0;System.out.println(k / n);

    System.out.println(k + n);

    } // trycatch (Exception e)

    { System.err.println(e.toString());System.err.println(e.getMessage());

    } // catch

    System.out.println(Press any key to exit.);System.in.read();

    } // main

    } // Catch1

    The output produced by the above program is:

    java.lang.ArithmeticException: / by zero/ by zero

    I/O Classes by CategoriesIn general, input and output are treated as a sequence of bytes or characters; hence, a stream. In

    Java, all input and output operations are handled as streams, either as a stream of bytes or a

    stream of characters. Java I/O classes are divided into byte stream classes and character

    stream classes. Java I/O classes can be divided into two generations: JDK 1.0 and JDK 1.1.

    The classjava.io.InputStream andjava.io.OutputStream are the two top byte stream classes,as shown in the following inheritance trees. By functionality, streams are categorized intostandard I/O streams and file I/O streams. Manipulation on byte streams is assumed to be

    sequential. In order to manipulate file streams in a random fashion, the

    java.io.RandomAccessFile class is used.

    java.lang.Object java.lang.Object java.lang.Object

    | | |

  • 7/29/2019 Exception Handling.doc

    3/86

    - 3 - Dr. Yaos CS 214 Class Notes #2

    +-- InputStream +-- OutputStream +-- RandonAccessFile

    To support stream operations, Java has several interfaces, including top level interfaces

    DataInput, DataOutput, and sub-level interfaces ObjectInput, and ObjectOutput. For

    example, the java.io.RandomAccessFile is derived directly rom java.lang.Object and implementsthe DataInput and DataOutput interfaces in order to support both reading and writing to a

    random access file. A random access file is treated as a large array of bytes stored in the file

    system.

    Thejava.io.Reader andjava.io.Writer classes, introduced by JDK 1.1, are the two topcharacterstream classes. In addition, thejava.io.StreamTokenizer class takes an input stream

    and parses it into "tokens", allowing the tokens to be read one at a time. The inheritance treesare:

    java.lang.Object java.lang.Object java.lang.Object

    | | |+--java.io.Reader +--java.io.Writer +-- java.io.StreamTokenizer

    Java provides a rich set of stream classes for input and output operations. All these stream

    classes are defined in java.io package and are categorized into byte streams and character

    streams. The InputStream and OutputStream are the top classes of all byte stream

    subclasses. Reader and Writer classes are the top classes for character stream subclasses. The

    overall inheritance hierarchies are shown below.

    Byte Stream Classes

    java.io.InputStream

    |

    +-- ByteArrayInputStream+-- FileInputStream

    +-- FilterInputStream

    |+-- BufferedInputStream

    +-- DataInputStream ------------------------------------->>>> DataInput+-- LineNumberInputStream

    +-- PushBackInputStream+-- ObjectInputStream --------------------------------------->>>> ObjectInput+-- PipeInputStream

    +-- SequenceInputStream+-- StringBufferInputStream

    java.io.OutputStream

    |

    +-- ByteArrayOutputStream

    +-- FileOutputStream

  • 7/29/2019 Exception Handling.doc

    4/86

    - 4 - Dr. Yaos CS 214 Class Notes #2

    +-- FilterOutputStream

    |

    +-- BufferedOutputStream+-- DataOutputStream ------------------------------------->>>> DataOutput+-- PrintStream

    +-- ObjectOutputStream -------------------------------------------->>>> ObjectOutput+-- PipeOutputStream

    Character Stream Classes

    java.io.Reader

    |

    +-- CharacterArrayReader

    +-- InputStreamReader

    |

    +-- FileReader+-- FilterReader

    |+-- PushBackReader

    +-- StringReader

    +-- PipeReader+-- BufferedReader

    |

    +-- LineNumberReader

    java.io.Writer

    |

    +-- BufferedWriter

    +-- CharacterArrayWriter+-- OutputStreamWriter

    |

    +-- FileWriter+-- FilterWriter

    +-- PipeWriter

    +-- PrintWriter

    +-- StringWriter

    java.io.File Class

    In addition to byte stream classes and character stream classes, thejava.io.File class (deriveddirectly from java.lang.Object class) presents an abstract, system-independent view of

    hierarchical pathnames. Hence, it is an abstract representation offile and directory pathnames.

    An abstract pathname has two components:1. An optional system-dependent prefix string, such as a disk-drive specifier, "/" for the

    UNIX root directory, or "\\" for a Win32 pathname.

    2. A sequence of zero or more string names.

    A pathname can be either an absolute path or a relative path to the currently directory.

  • 7/29/2019 Exception Handling.doc

    5/86

    - 5 - Dr. Yaos CS 214 Class Notes #2

    In summary, the java.io package contains a collection of stream classes that support these

    algorithms for reading and writing streams. These classes are divided into two class hierarchiesbased on the data type (either characters or bytes) on which they operate, as depicted by the

    below figure. Other stream classes are also present to support special stream operations, such as

    the RandomAccessFile class. A collection of interfaces are also found in thejava.io package inorder to standardize and ease file stream manipulations, such as file/directory path and object

    serialization.

    Reading File Streams

    All file streams are automatically opened when created. You can close any stream explicitly by

    calling its close() method. Otherwise, the garbage collector can implicitly close it. The characterand byte streams are all sequential access streams. In JDK 1.0, DataInputStream along with

    FileInputStream is to read from a file -- these classes will raise a deprecation warning message.

    DataInputStream myfile = new DataInputStream(new FileInputStream(file-path));

    To eliminate the deprecation message, the BufferedReader and FileReader are recommended:BufferedReader infile = new BufferedReader(new FileReader(file-path));

    The next program demonstrates how a file is opened for reading. It reads a line from the inputfile and displays counters for lowercase letters, uppercase letter, and spaces found in the input

    line.

    // CountChar.java

    import java.io.*;

    /**

    * This program demonstrates: File input manipulation.* It counts and display the number of lowercase letters, the number of uppercase letters, and

    * the number of spaces on each input line. A line number is also displayed.

    * @author: Andy Yao, Ph.D.*/

    public class CountChar{/**

    * Sequential file access.

    * If DataInputStream along with FileInputStream is used, a deprecation message will be raised.

    * BufferedReader along with FileReader should be used to process the input file.* The input file is the program source code itself.

    * @param upper is the counter for uppercase letters.

    * @param lower is the counter for uppercase letters.* @param spaces is the counter for uppercase letters.

    * @param linecnt keeps track of the line number.

    */public static void main(String []args) throws IOException

    {

    // DataInputStream infile; // deprecated

    BufferedReader infile;

  • 7/29/2019 Exception Handling.doc

    6/86

    - 6 - Dr. Yaos CS 214 Class Notes #2

    String line;

    int upper, lower, spaces, k, linecnt = 0;

    char c;try

    {

    //infile = new DataInputStream(new FileInputStream("employee.java")); // deprecatedinfile = new BufferedReader(new FileReader("employee.java"));// Call readLine() method to read a line from the input file stream.

    while ((line = infile.readLine()) != null) // A null denotes the end of file condition is true.{

    ++linecnt; // The line count

    upper = lower = spaces = 0;for (k=0; k < line.length(); ++k) // Step through the input line, character by character.

    {

    c = line.charAt(k); // get one character

    if ((c >= 'a') && c = 'A') && c

  • 7/29/2019 Exception Handling.doc

    7/86

    - 7 - Dr. Yaos CS 214 Class Notes #2

    Uppercase: 2 Lowercase: 8 Spaces: 7

    4: Dave 38729.15 Programmer

    Uppercase: 2 Lowercase: 12 Spaces: 6

    The next program shows how to process input file stream and use StringTokenizer to split a line

    into fields. Fields of the input lines are separated by spaces. It is a common practice that aninput file is processed as a sequence of bytes and read into a String object on line by line basis.

    The input String then is processed using other utilities, such as StringTokenizer.

    // ReadFile.java

    import java.io.*;

    import java.util.*;

    /*** Demonstrates the file reading operation and the use of StringTokenizer.

    * Reads the data file line by line and parses each line into tokens (fields).

    * These tokens are saved in three separate String arrays.

    * This program also calculates and displays the total salary of all employees.* Assumption: The input file is located under the current working directory.

    * Listed below are two sample input lines:* Wesley 49287.52 Programmer

    * Addison 38929.20 Analyst

    * @author: Andy Yao, Ph.D.*/

    public class ReadFile

    {

    static BufferedReader infile;static String line;

    static int k = 0;

    static String []name = new String[100];static String []title = new String[100];

    static double []salary = new double[100];

    public static void main(String []args)

    {

    try

    {

    infile = new BufferedReader(new FileReader("employee.dat"));

    while ((line = infile.readLine()) != null)

    {saveRec(line, k); // save the input line into 3 arrays.

    ++k;

    } // while

    infile.close();

    } // try

    catch (IOException x) {

    System.err.println(x.toString());

  • 7/29/2019 Exception Handling.doc

    8/86

    - 8 - Dr. Yaos CS 214 Class Notes #2

    System.exit(1);

    } // catch

    printRec(k); // Print the output} // main

    // Using StringTokenizer to split a line into fields.static void saveRec(String s, int k)

    {

    // Split the line into fields.StringTokenizer record = new StringTokenizer(s);

    name[k] = record.nextToken(); // name

    // Covert the salary in String into double.

    salary[k] = Double.valueOf(record.nextToken()).doubleValue();title[k] = record.nextToken();

    } // saveRec

    // Displays the records and the total salary for all employees.static void printRec(int size)

    {double total = 0;

    for (int k=0; k < size; ++k)

    {total = total + salary[k];

    System.out.println(name[k] + " " + title[k] + " " + salary[k]);

    }

    System.out.println("Total salary: " + total);} // printRec

    } // ReadFile

    The output generated by the above program,ReadFile.java, is:

    Lynda Clerk 38726.89

    Eva Programmer 49287.52

    Ava Analyst 38929.2

    Dave Programmer 38729.15

    Total salary: 165672.76

    The above program, ReadFile.java, uses thejava.io.BufferedReader class to process an input

    file. Thejava.io.BufferedReader is directly derived form thejava.io.Reader abstract class:

    +--java.io.Reader

    |

    +--java.io.BufferedReader

  • 7/29/2019 Exception Handling.doc

    9/86

    - 9 - Dr. Yaos CS 214 Class Notes #2

    The java.io.BufferedReader has two constructors:

    BufferedReader(Readerin);// Create a buffering character-input stream that uses a default-sized input buffer.

    BufferedReader(Readerin, int size);

    // Create a buffering character-input stream that uses an input buffer of the specifiedsize.

    Listed below are some of the commonly usedjava.io.BufferedReader methods:

    int read() ; // Read a single character. Return -1 at the end of the stream.String readLine(); // Read a line of text. Return a null at the end of the file.

    long skip(long n);// Skip n characters.

    boolean ready(); // Indicates whether this stream is ready to be read.

    The parameter in to the BufferedReader constructors can be an object created from any

    subclass of thejava.io.Reader class. In a general practice, we need a class which takes either a

    file path or file descriptor to create a Reader stream object. Thejava.io.FileReader (see

    inheritance tree below) has the following three constructors and can be used for such a purpose:

    FileReader(String filepath); java.io.Reader FileReader(File file); |

    FileReader(FileDescriptor fd); +--java.io.InputStreamReader

    |+--java.io.FileReader

    The general statements used to process a file stream using the java.io.BufferedReader are:

    BufferedReader infile = new BufferedReader(new FileReader(.........));

    String line;

    while ((line = infile.readLine()) != null) // read a line...................

    or

    BufferedReader infile = new BufferedReader(new FileReader(.........));

    int c;

    while ((c = infile.read()) != -1) // read a character

    ...................

    The next program uses the read() method to process the input file one character at a time. It is

    essential that the value returned by the read() method must be converted into a character for

    output. Replacing Statement A by String line; and Statement B by

    while ((line = infile.readLine()) != null)

    System.out.println(line);

    will achieve the same goal and produce the same output.

  • 7/29/2019 Exception Handling.doc

    10/86

    - 10 - Dr. Yaos CS 214 Class Notes #2

    ReadFile2.javaimport java.io.*;

    /*** Demonstrates the file reading operation.

    * This program displays a file by reads

    * one character at a time.

    */public class ReadFile2 {

    public static void main(String []args)

    {BufferedReader infile;

    int c; // Statement Atry{

    infile = new BufferedReader

    (new FileReader("employee.dat"));

    /* read() returns the integer equivalence of

    the input character or -1 when the end offile stream is reached. */

    // Statement Bwhile ((c = infile.read()) != -1)

    // covert to a character for outputSystem.out.print((char) c);

    infile.close();

    } // trycatch (IOException x)

    {System.err.println(x.toString());System.exit(1);

    } // catch

    } // main} // ReadFile2

    Writing File Streams

    To process an output file stream (writing to a file), we, again, have many options. Presented in

    this section are two different options. The first option is to use thejava.io.BufferedWriter andjava.io.FileWriter classes.

    WriteFile.java

  • 7/29/2019 Exception Handling.doc

    11/86

    - 11 - Dr. Yaos CS 214 Class Notes #2

    // Writing to a file stream using BufferedWriter and FileWriter classes.

    import java.io.*;public class WriteFile{

    public static void main(String []args) {

    BufferedWriter outfile; // Line 5try

    {

    outfile = new BufferedWriter(new FileWriter("output1.dat")); // Line 8

    outfile.write("Hello, world!"); // Line 9outfile.close();

    } // trycatch (IOException x)

    {

    System.err.println("Error: " + x.toString());System.exit(1);

    } // catch} // main} // WriteFile

    The second option is to use thejava.io.DataOutputStream and java.io.FileOutputStream,

    andjava.io.File classes; i.e., modifying the above to replace Line 5 by

    DataOutputStream outfile;

    Line 8 by DataOutputStream outfile = new DataOutputStream(

    new FileOutputStream(new File("output2.dat")));

    and Line 9 by

    outfile.writeBytes(Hello, world!);

    Thejava.io.BufferedWriter class is derived directly from thejava.io.Writer abstract class andhas two constructors:

    // Create a buffered character output stream that uses a buffer of the default size.

    BufferedWriter(Writerout);

    // Create a buffered character output stream, using an output buffer of the given size.BufferedWriter(Writerout, int size);

    The parameter out can be an object created from any subclass of thejava.io.Writer class. In a

    general practice, an object is created from the java.io.BufferedWriter file for this purpose.Three commonly usedjava.io.BufferedWriter methods are listed below.

    void write(int c); // Write a single character.

    void write(String str); // Write a string.void write(char[] buf); // Write an array of characters.

    The inheritance tree and constructors for thejava.io.FileWriter class are listed below.FileWriter(String filepath); java.io.Writer

    FileWriter(File file); |

    FileWriter(FileDescriptor fd); +--java.io.OutputStreamWriter

  • 7/29/2019 Exception Handling.doc

    12/86

    - 12 - Dr. Yaos CS 214 Class Notes #2

    FileWriter(String name, boolean append); |

    +--java.io.FileWriter

    If one of the first three constructors is used to create a FileWriter file stream object, a new file is

    created, truncating the original file contents if the file exists. The last constructor may be used

    to set the append flag to true, if it is so desired to keep the original file contents and to appendto the end of the existing file, as demonstrated by the following program,AppendFile.java.

    AppendFile.java// Appending to an existing file stream.import java.io.*;

    public class AppendFile {

    public static void main(String []args) {

    BufferedWriter outfile;try {

    // open a file for appending

    outfile = new BufferedWriter

    (new FileWriter("output1.dat", true));

    outfile.write("A new line");outfile.close();

    } // try

    catch (IOException x) {

    System.err.println(x.toString());System.exit(1);

    } // catch

    } // main

    } // AppendFile

    The following Java standalone application, SaveFile.java, saves the text lines entered by the user

    in a TextArea object into a file stream. This program uses a Frame object as its container to holdGUI objects. Generally, an applet is a subclass derived from either thejava.applet.Applet class

    orjava.swing.JApplet class; whereas a standalone application uses a Frame or JFrame class to

    create a top-level container.

    // SaveFile.java

    import java.awt.*;

    import java.awt.event.*;import java.io.*;

    /*** This GUI based program saves the text entered in a TextArea to a file.

    * The output file is under the current working directory.

    * This is a standalone application, using Frame as the GUI container.*/

    public class SaveFile extends Frame implements ActionListener

    {TextArea inarea;

    Button save;

    public static void main(String []args)

    {

    SaveFile x = new SaveFile(); // create an instance

    x.setSize(200, 250); // set the Frame sizex.setVisible(true); // make the Frame show

    } // main

  • 7/29/2019 Exception Handling.doc

    13/86

    - 13 - Dr. Yaos CS 214 Class Notes #2

    /*

    * Tasks of the constructor are:

    * sets up the frame title and Layout manager* creates a Button and a TextArea

    * attach GUI objects to event listener

    * adds the GUI objects to the Frame**/

    public SaveFile() { // constructor

    setTitle("File Output"); // set the Frame titlesetLayout(new GridLayout(2, 1));

    inarea = new TextArea(10, 30);

    add(inarea);

    save = new Button("Save");save.addActionListener(this); // Register to the event listener

    add(save);

    } // constructor

    public void actionPerformed(ActionEvent e) {

    if (e.getSource() == save){

    try

    {// Statement A BufferedWriter outfile = new BufferedWriter(new FileWriter("output.dat"));// Statement B

    // BufferedWriter outfile = new BufferedWriter(new FileWriter("output.dat", true));outfile.write(inarea.getText());

    outfile.close();

    inarea.setText("");} // try

    catch (IOException x)

    {System.err.println(x.toString());

    System.exit(1);

    } // catch

    } // if} // actionPerformed

    } // SaveFile

    The Statement A can be replaced by the Statement B, if the original file contents need to be

    saved; thus, appending to the file.

    // BothIO.java

  • 7/29/2019 Exception Handling.doc

    14/86

    - 14 - Dr. Yaos CS 214 Class Notes #2

    // This program combines both input and output operations.

    import java.awt.*;

    import java.awt.event.*;

    import java.io.*;/**

    * This GUI based program saves the text entered in a TextArea to a file.

    * It also reads from a text file into a second TextArea, using* BufferedReader and FileReader classes.

    * The input and output file are under the current working directory.

    * This is a standalone application, using Frame as the GUI container.

    */public class BothIO extends Frame implements ActionListener

    {

    TextArea inarea, outarea;

    Button save, read;/*

    * Tasks of the constructor are:* sets up the frame title and Layout manager

    * creates Buttons and TextAreas

    * attach GUI objects to event listener* adds the GUI objects to the Frame

    **/

    public BothIO() // constructor

    {setTitle("File Output"); // set the Frame title

    setLayout(new GridLayout(2, 2));

    inarea = new TextArea(10, 30);add(inarea);

    save = new Button("Save");

    save.addActionListener(this); // Register to the event listeneradd(save);

    outarea = new TextArea(10, 30);

    outarea.setEditable(false); // output only

    add(outarea);read = new Button("Read");

    read.addActionListener(this); // Register to the event listener

    add(read);} // constructor

    public static void main(String []args){

    BothIO x = new BothIO(); // create an instance

    x.setSize(200, 250); // set the Frame size

    x.setVisible(true); // make the Frame show

  • 7/29/2019 Exception Handling.doc

    15/86

    - 15 - Dr. Yaos CS 214 Class Notes #2

    } // main

    public void actionPerformed(ActionEvent e) {String line;

    if (e.getSource() == save)

    {try

    { // write to a text file

    FileOutputStream os = new FileOutputStream(new File("myOutput.dat"));

    DataOutputStream outfile = new DataOutputStream(os);

    outfile.writeBytes(inarea.getText());

    outfile.close();

    inarea.setText("");} // try

    catch (IOException x)

    {

    System.err.println("Error: " + x.toString());System.exit(1);

    } // catch} // if save

    if (e.getSource() == read){try

    { // Read from a text file

    BufferedReader infile = new BufferedReader(new FileReader("myOutput.dat"));

    while ((line = infile.readLine()) != null)outarea.append(line + "\n");

    infile.close();

    } // trycatch (IOException x)

    {

    System.err.println("Error: " + x.toString());System.exit(1);

    } // catch

    } // if read

    } // actionPerformed} // BothIO

    Random Access FileThejava.io.RandomAccessFile class supports the random file access:

    public class RandomAccessFile extends Object implements DataOutput,

    DataInput

    Instances of thejava.io.RandAccessFile class support both reading from and writing to a

    random access file. A random access file behaves like a large array of bytes stored in the file

  • 7/29/2019 Exception Handling.doc

    16/86

    - 16 - Dr. Yaos CS 214 Class Notes #2

    system. There is a kind of cursor, or index into the implied array, called thefile pointer. Input

    operations read bytes starting at the file pointer and advance the file pointer past the bytes read.

    If the random access file is created in read/write mode, then output operations are also available.Output operations write bytes starting at the file pointer and advance the file pointer past the

    bytes written. Output operations that write past the current end of the implied array cause the

    array to be extended. The file pointer can be read by the getFilePointer() method and moved/setby the seek() method.

    Thejava.io.RandomAccessFile class implements both the DataInput and DataOutputinterfaces and therefore can be used for both reading and writing. When creating an instance of

    thejava.io.RandomAccessFile class, you must indicate whether you wish to read from the file,

    write to the file, or both. For example, the following statement opens a random file for reading

    new RandomAccessFile("myfile.txt", "r");The next statement opens the a file for both reading and writing:

    new RandomAccessFile("myfile.txt", "rw");

    After the file is opened, you can use the readXXX orwriteXXX methods to perform I/O on the

    file. Thefile pointerindicates the current cursor or index location in the file. When the file is

    first created, the file pointer is 0, indicating the beginning of the file. Calls to the readXXX and

    writeXXX methods adjust the file pointer by the number of bytes read or written. The

    RandomAccessFile class provides three methods for explicitly manipulating the file pointer.

    skipBytes Moves the file pointer forward the specified number of bytes.

    seek Positions the file pointer just before the specified byte.

    getFilePointer Returns the current byte location of the file pointer.

    To randomly access to a file, the RandomAccessFile class is used. This class provides the

    methods for reading and writing a file at a specific location. To move the read/write header(pointer), the seek() method is used. A random-access file can be opened either for read-only or

    for read/write. The next program Randomio.java illustrates the use of the RandonAccessFileclass and its methods to manipulate the file contents in a random fashion.

    Method: public RandomAccessFile(String filename, String access-mode)

    Description: The constructor which is used to instantiate a RandomAccessFile object.

    filename the file path

    access-mode: r for reading; rw for read/write.

    Method: public long length()

    Description: This method returns the size of the file in byte (long).

    Method: public void seek(long where)

    Description: It moves the read/write pointer to where.

    Method: writeBytes(String s)

    Description: This method writes s to the file.

  • 7/29/2019 Exception Handling.doc

    17/86

    - 17 - Dr. Yaos CS 214 Class Notes #2

    Method: readLine()

    Description: This method reads a line from the file and returns the line as a String. It returns anull when the end of file condition becomes true.

    Method: public void close()

    Description: This method is used to close the file.

    The next program (RandomIO.java), displays the following lines on the monitor.

    Hello, world

    Hello, A New line

    ------- Final result ----

    Hello, A New line

    How wonderful

    Hence, the file Random.DAT will contain two lines:Hello, A New line

    How wonderful

    // RandomIO.java

    // Random file I/O operations

    import java.io.*;

    public class RandomIO

    {

    static String filename = "A:Random.DAT";

    public static void main(String []args)

    {

    try

    {

    append("Hello, world\n");

    showit();

    update(7, "A New line\n");

    showit();

    append("How wonderful");

    System.out.println("---- Final result ----");

    showit();

    } // try

    catch(Exception x)

  • 7/29/2019 Exception Handling.doc

    18/86

    - 18 - Dr. Yaos CS 214 Class Notes #2

    {

    System.err.println(x.toString());

    System.exit(1);

    } // catch

    } // main

    static void append(String msg)

    throws IOException

    { // append "msg" to the end of the file

    RandomAccessFile myfile;

    try

    {

    myfile = new RandomAccessFile(new File(filename), "rw");

    myfile.seek(myfile.length());

    myfile.writeBytes(msg);

    myfile.close();

    } // try

    catch (Exception x)

    {

    System.err.println(x.toString());System.exit(1);

    }

    } // append

    static void update(long where, String s) throws IOException

    { // Write "s" to the file at "where"

    RandomAccessFile myfile;

    try

    {

    myfile = new RandomAccessFile

    (new File(filename), "rw");

    if (where > myfile.length())

    where = myfile.length();

  • 7/29/2019 Exception Handling.doc

    19/86

    - 19 - Dr. Yaos CS 214 Class Notes #2

    myfile.seek(where);

    myfile.writeBytes(s);

    myfile.close();

    } // try

    catch (Exception x)

    {

    System.err.println(x.toString());

    System.exit(1);

    }

    } // insert

    static void showit() throws IOException

    { // Displays the file contentsRandomAccessFile myfile;

    try

    {

    String line;

    myfile = new RandomAccessFile

    (new File(filename), "r");

    while ((line = myfile.readLine()) != null)

    System.out.println(line);myfile.close();

    } // try

    catch (Exception x)

    {

    System.err.println(x.toString());

    System.exit(1);

    }

    } // showit

    } // RandomIO

  • 7/29/2019 Exception Handling.doc

    20/86

    - 20 - Dr. Yaos CS 214 Class Notes #2

    The java.io.File Class

    The File class is an abstract representation of file and directory path name. User interfaces andoperating systems use system-dependent path name (a sequence of characters) to name files and

    directories. The File class presents an abstract, system-independent view of hierarchical path

    names. An abstract path name has two components:

    ? An optional system-dependent prefix string, such as C: as a disk-drive specifier, or /

    for the UNIX root directory

    ? A sequence of string names

    The conversion of a path name string to or from an abstract path name is system-dependent.When an abstract path name is converted into a path name string, each name is separated from

    the next by a single copy of the default separator character. The default name-separator

    character is defined by the system property file separator. When a path name string is converted

    into an abstract path name, the names within it may be separated by the default name-separator

    character or by any other name-separator character that is supported by the underlying system.

    A path name, whether abstract or in string form, may be eitherabsolute orrelative. An absolutepath name is complete in that no other information is required in order to locate the file that it

    denotes. A relative path name, in contrast, must be interpreted in terms of information taken

    from some other path name. By default the classes in the java.io package always resolve relativepath names against the current working directory. This directory is named by the system

    property user.dir, and is typically the directory in which the Java virtual machine was invoked.

    Instances of thejava.io.File class are immutable; that is, once created, the abstract path namerepresented by ajava.io.File object will never change.

    The following program, MyDir.java, displays the files and subdirectories of the current

    directory. The list() method of thejava.io.File class is used to retrieve the file/directory list.

    String[] list(); // return a list of file/directory names.

    This program works like the DIR command in MS/DOS or the ls command in UNIX.

    MyDir.java

  • 7/29/2019 Exception Handling.doc

    21/86

    - 21 - Dr. Yaos CS 214 Class Notes #2

    // Using the java.io.File class to display files/directories

    // under the current working directory.import java.io.*;

    public class MyDir {

    public static void main(String []args) {

    String []dirList;try

    { File mypath = new File("."); // current directory

    dirList = mypath.list(); // get the file list

    for (int k=0; k < dirList.length; ++k)

    System.out.println(dirList[k]);} // try

    catch(Exception e)

    {e.printStackTrace();

    System.exit(2);}} // main

    } // MyDir

    Let us modify the previous program, MyDir.java, to take the first command line argument as

    the directory, instead of the current directory. The synopsis for running this program is:

    MyDir2 DirectoryName

    The modified program, MyDir2.java, is shown below.

    MyDir2.java

  • 7/29/2019 Exception Handling.doc

    22/86

    - 22 - Dr. Yaos CS 214 Class Notes #2

    // Using the java.io.File class to display files/directories

    // under the directory specified as a command line argument.// Synopsis: MyDir2DirectoryName

    import java.io.*;

    public class MyDir2 {

    public static void main(String []args) {String []dirList;

    try{

    if (args.length != 1) // expecting 1 command line argument

    {

    System.err.println("Please specify a directory");System.exit(1);

    }

    File mypath = new File(args[0]);

    dirList = mypath.list(); // get the file/directory list

    for (int k=0; k < dirList.length; ++k)System.out.println(dirList[k]);} // try

    catch(Exception e)

    {e.printStackTrace();

    System.exit(2);

    }

    } // main} // MyDir2

    Object SerializationThe term object serialization means (1) converting all attributes (states) of an object into a

    sequence of bytes and (2) saving this sequence bytes into as an object stream. An object streamis not necessarily a file stream. Such a mechanism can thus be used to prepare an object for

    transmission across networks and operating systems. The java.io.Serializable interface is

    designed for such purposes and, thus, can be used to implement the object persistence and

    portability. Data Persistence means that the lifetime of an object is not determined by whether

    the program is running or that an object lives in between the invocation of programs, such as a

    client application (an applet or a standalone application) and a server-side program (a servlet).

    Data Portability means that objects can be retrieved by Java programs running under different

    operating system or networking environment, as long as the data class is accessible.

    The serializability of a class is done by implementing the java.io.Serializable interface.Subclasses of a serializable class are also serializable, too. The Serializable interface has no

    methods or attributes (fields) and serves only to identify the semantics of being serializable. By

    functionality, Java classes can be group into: User interface or driver classes and Data classes.The data classes are to represent the objects in interest and should be coded to have the ability to

    be serialized. Thus, the syntax:

  • 7/29/2019 Exception Handling.doc

    23/86

    - 23 - Dr. Yaos CS 214 Class Notes #2

    public class ClassName implements Serializable { ........ }

    Classes that require special handling or operation for the object serialization and de-serializationwill need to implement the writeObject() and readObject() methods. The signatures of these

    java.io.Serializable interface are:

    void writeObject(java.io.ObjectOutputStream out);

    void readObject(java.io.ObjectInputStream in);

    In general practice, classes that need to ensure its objects can be serialized will simply include

    the implements Serializable expression as shown above and will not need to specifically define

    the Serializable.writeObject() orSerializeable.readObject() methods. It is essential to realize

    that serialization is actually performed by special kind of stream objects, generally known asobject streams: ObjectOutputStream for serialization and ObjectInputStream for de-

    serialization). The java.io.ObjectOutputStream.writeObject() and

    java.io.ObjectInput.readObject() methods are used to actually serialize and de-serialize

    objects. The writeObject() method is responsible for writing the state of the object for itsparticular class so that the readObject() method will be able to restore (deserialize) it. Thus,

    object state is saved by writing the serializable attributes/fields to the

    java.io.ObjectOutputStream object using the writeObject() method. Attributes declared as

    static or transient cannot and will not be serialized. On the other hand, the readObject()method is used to retrieve (restore) the state of an object from anjava.io.ObjectInputStream.

    Serializing an object

    Objects are serialized by writing them to an object stream, for example:

    // Serialize today's date to a file stream.

    FileOutputStream outfile = new FileOutputStream("mytmpfile");

    ObjectOutputStream out = new ObjectOutputStream(outfile);out.writeObject(new Date()); // serialize a Date object

    out.flush(); // or out.close();

    The signature for the constructor is:

    ObjectOutputStream(OutputStreamout);

    Thus, out can be any object created from any subclass of the java.io.OutputStream class; inthe case, a FileOutputStream object. The writeObject() method is then invoked to store the

    state of the object. Many objects can be saved to the same ObjectOutputStream. The sequence

    in which the objects are saved will be followed by the

    java.io.ObjectInputStream.readObject() method for de-serialization. The signature for the

    writeObject() method is:

    void writeObject(Object obj);The java.io.ObjectOutputStream class provides a rich set of methods, such as writeInt(),

    writeDouble(),.... for object serialization. However, the writeObject() is probably the most

    commonly used method.

    De-serializing an object

    To reverse the process, the following is a typical temple.

  • 7/29/2019 Exception Handling.doc

    24/86

    - 24 - Dr. Yaos CS 214 Class Notes #2

    // Deserialize a date from a file stream.

    FileInputStream infile = new FileInputStream("mytmpfile");

    ObjectInputStream in = new ObjectInputStream(infile);

    Date date = (Date) in.readObject();

    Ajava.io.ObjectInputStream, in this a FileInputStream, is needed as the source stream for anobject de-serialization. The state of an object is read/retored from the stream. Generally, objectsare read with the readObject() method. Objects will be de-serialized in the sequence they were

    serialized. Of course, thejava.io.ObjectInputStream class also provides other de-serialization

    methods, such as readInt(), readChar(),...... To demonstrate the serialization and de-

    serialization of objects, let us develop a class, named EmpRec, to represent employee records,and then develop two programs to serialize some EmpRec objects and de-serialize the serialized

    EmpRec objects. A file stream is used for storing the attributes of these EmpRec objects.

    EmpRec.java

    // EmpRec class represents the employee information.

    // EmpRec is a serializable class./* A class should provide a set of methods: constructor, readers, and writers.

    Usually, a pair of reader and writer methods is provided for each attribute.The toString() method defined in Object class is a typical reader method. */

    import java.io.*;

    public class EmpRec implements Serializable { // attributes

    int ID; // employee IDString name; // employee name

    public EmpRec(int v, String s) // constructor {

    setID(v);setName(s); }

    // reader and writer methodspublic String toString() // reader method defined in root class{ return name + ID; } // toString -- defined in Object class

    public void setID(int v) { ID = v; }

    public int getID() { return ID; }

    public void setName(String s) { name = s; }public String getName() { return name; }

    } // EmpRec

    The expression implement serializable makes all objects created from the EmpRec class and

    its subclasses to be serializable. The next program, SaveEmp.java, is to create some EmpRec

    objects and serialize them into a file. SaveEmp.java

  • 7/29/2019 Exception Handling.doc

    25/86

    - 25 - Dr. Yaos CS 214 Class Notes #2

    // Serializing EmpRec objects into a file stream emp.out.

    // This program writes/serializes two EmpRec objects to an ObjectOutputStream.import java.io.*;

    public class SaveEmp {

    public static void main(String[] args) {

    EmpRec emp1 = new EmpRec(99, "Lynda");EmpRec emp2 = new EmpRec(88, "Ava");

    try {// Create an ObjectOutputStream object for serialization..

    ObjectOutputStream out =new ObjectOutputStream(new FileOutputStream("emp.out"));

    // Write the objects to the file "emp.out" out.writeObject(emp1);

    out.writeObject(emp2);

    out.close();} // try catch (Exception e) { e.printStackTrace(); System.exit(1); }

    } // main} // SaveEmp

    When executed, the above program, SaveEMp.java, writes two EmpRec objects into the fileemp.out located under the current directory. The MS/DOS command type emp.out or the

    UNIX command cat emp.out can be used to verify that the objects are serialized. The file

    emp.out is considered to contain binary data. The following program, ReadEmp.java, de-

    serialize the EmpRec objects serialized by the previous program, SaveEmp.java.

    ReadEmp.java

    // De-serializes the EmpRec objects serialized by SaveEmp.java.

    // This program de-serializes two EmpRec objects from an ObjectInputStream.import java.io.*;public class ReadEmp {

    public static void main(String[] args) {

    EmpRec x;

    try {// Create an ObjectInputStream for object de-serialization.

    ObjectInputStream in =

    new ObjectInputStream(new FileInputStream("emp.out"));// Read and deserialize the objects from the file "emp.out"

    x = (EmpRec) in.readObject();

    System.out.println(x.toString());x = (EmpRec) in.readObject();

    System.out.println(x.toString());

    in.close(); } // trycatch (Exception e) { e.printStackTrace(); System.exit(1); }

    } // main

    } // ReadEmp

  • 7/29/2019 Exception Handling.doc

    26/86

    - 26 - Dr. Yaos CS 214 Class Notes #2

    To test the above two programs, SaveEmo and ReadEmp, let us develop a standalone application

    which invokes SaveEmp.main() and ReadEmp.main() to first save a couple of EmpRec objects

    and later retrieve them.

    EmpDriver.java

    // A driver class used to test ReadEmp and SaveEmppublic class EmpDriver{public static void main(String[] args)

    {

    String [] x = new String[2];

    System.out.println(Saving....); SaveEmp.main(x);System.out.println(Reading....);

    ReadEmp.main(x);} // main

    } // EmpDriver

    C:\>javac EmpDriver.javaC:\>java EmpDriver

    Saving....

    Reading....

    Lynda99

    Ava88

    Using the JAR commandIn software development, an archive file is generally known as a file which consists of acollection of compiled codes (bytes codes in Java). Thejar command is used to manipulate Java

    archive files. Shown below are: (1) creating a jar file, (2) extracting from a jar file, and (3) using

    a jar file. In order to use a jar file, it is necessary to update the CLASSPATH variable to include

    the jar file path/name.

    (1) Create a jar file, named fileA.jar, to contain three bytecodes: SaveEmp, ReadEmp, andEmpRec:C:\>jar cvf fileA.jar SaveEmp.class ReadEmp.class EmpRec.classadded manifest

    adding: SaveEmp.class(in = 786) (out= 498)(deflated 36%)adding: ReadEmp.class(in = 857) (out= 512)(deflated 40%)

    adding: EmpRec.class(in = 878) (out= 472)(deflated 46%)

  • 7/29/2019 Exception Handling.doc

    27/86

    - 27 - Dr. Yaos CS 214 Class Notes #2

    (2) Extracting from the jar file generated from the above step:

    C:\> mkdir temp

    C:\> cd tempC:\>jar xvf ..\fileA.jarcreated: META-INF/

    extracted: META-INF/MANIFEST.MFextracted: SaveEmp.class

    extracted: ReadEmp.class

    extracted: EmpRec.class

    As an example, this step is done in a different directory from the original directory.

    (3) Using a jar file does not require the jar file contents to be extracted. However, the

    CLASSPATH must be either updated or specified to include a jar file for the programcompilation and execution.

    C:\> cp ..\EmpDriver.java

    C:\> rm *..class javac -classpath .;..\fileA.jar EmpDriver.javaC:\>java EmpDriverSaving....

    Exception in thread "main" java.lang.NoClassDefFoundError: SaveEmpat EmpDriver.main(EmpDriver.java:8)

    C:\>java -classpath .;..\fileA.jar EmpDriverSaving...

    Reading..

    Lynda99

    Ava88

    Notice that the CLASSPATH option is used in both compiling and running the above program.

    To list the options of the jar command:

    C:\>jar

    Usage: jar {ctxu}[vfm0M] [jar-file] [manifest-file] [-C dir] files ...Options:

    -c create new archive

    -t list table of contents for archive

    -x extract named (or all) files from archive

  • 7/29/2019 Exception Handling.doc

    28/86

    - 28 - Dr. Yaos CS 214 Class Notes #2

    -u update existing archive

    -v generate verbose output on standard output

    -f specify archive file name-m include manifest information from specified manifest file

    -0 store only; use no ZIP compression

    -M Do not create a manifest file for the entries-C change to the specified directory and include the following file

    The jar command is also useful in creating a jar file for running a java program. To do so, amanifest file needs to be created to specify the name of the main class (driver class). The general

    steps are:

    Compile all java files into bytecodes

    C:\>java *.java

    Create a manifest file using a text editor, for example,

    mytest.txt

    Main-Class: EmpDriver

    C:\> jar cmf mytest.txt mytest.jar *.class

    C:\> java -jar mytest.jar

    Saving....

    Reading....

    Lynda99Ava88

    About GUI ApplicationsAll components of a GUI application in Java are derived from the class Component. A GUI

    application consists of two major parts: (1) User interface objects and (2) Graphics

    context/drawing. Thus, a GUI application must have a container to hold the user interfaceobjects and graphics context. Via the user interface objects user events can be created. The

    typical examples of user events are the mouse click and the keyboard activity. An applet is a

    client-side Java program which must run inside a web browser. The web browser, therefore,provides the necessary capabilities to manage the browsers window. An applet is simply to

    replace the document part of a web page. An applet itself is a container; however, it does not

    provide the capability to manipulate the window (web browser) that contains it. Hence, a GUIapplication must have a window-kind of container. But, a GUI application may have many

    containers. There are two major kinds of containers: window-kind and non-window-kind.

    Windows can further be divided into modal window (dialog window) and modeless window.

  • 7/29/2019 Exception Handling.doc

    29/86

    - 29 - Dr. Yaos CS 214 Class Notes #2

    Java AppletListed below is a Java Applet which must be brought up by an Internet browser and thus must be

    referenced to by an HTML page using and HTML tags. In otherwords, a Java applet is, in fact, a client application used in an Internet environment to provide

    dynamic features that are missing from HTML pages. An applet is known as a client-side Java

    application.

    // First2.java

    // An applet which display Hello, Welcome! at the specified (x, y) position.import java.awt.Graphics;

    import javax.swing.JApplet;

    public class First2 extends JApplet {public void paint(Graphics x) {

    x.drawString("Hello! Welcome!", 20, 25);

    } // paint

    } // First2

    RunFirst2.htm

    A Java applet is a class derived from the Applet or JApplet library class. An Internetbrowser expects certain properties (attributes and methods) from a Java applet; such properties

    should be transparent to the programmers and should have already been defined in a library

    class, such as Applet or JApplet. The Java programmer only needs to extend the libraryapplet to create a new applet to address the solution for the current task. This operation is termed

    as inheritance. In other words, a new applet inherits from the library applet class. Theinheritance syntax is:

    public class ClassName extends Applet {....}

    The Applet or JApplet class is referred to as a super class, a parent class, or a base class.

    The new class represented by ClassName is known as the derived class, sub class, or childclass. In the above example program, the class name is First2. The program should be saved

    in a file with the same name as the class. The statement import is used to indicate to the Java

    compiler that other classes from other packages will be used. Java library classes are saved intomany library packages. For example, the JApplet class is saved in the package javax.swing.

    Thus, one of the following statements is used:

    import javax.swing.*;import javax.swing.JApplet;

    In Java, a simple statement is terminated by a semicolon. A pair of braces is used to construct a

    compound statement; thus, the closing brace terminates a compound statement. The aboveprogram also uses the Graphics class of the java.awt package. The term awt stands for

    Abstract Windows Tools -- Javas GUI-based application programming interface. A Java

    applet is supposed to be presented by the Internet Browser as part of a HTML document and

  • 7/29/2019 Exception Handling.doc

    30/86

    - 30 - Dr. Yaos CS 214 Class Notes #2

    thus requires a corresponding HTML file to execute it. Most of the Java development tools will

    automatically generate an HTML file for such a purpose. Unlike the Java language, HTML is a

    case insensitive programming language. Each statement/directive is enclosed in a pair of anglebrackets and is termed as a tag. The tag indicates the name of the Java class

    ( bytecode). The width and height indicate the size of the applet. Thus, the above applet is

    of size 300 pixels by 80 pixels.

    Assuming both First2.java and runfirst2.htm files are saved under the same directory, the

    following steps compile and run the above Java applet.

    System Prompt>javac First2.java appletviewer runfirst2.htm

  • 7/29/2019 Exception Handling.doc

    31/86

    - 31 - Dr. Yaos CS 214 Class Notes #2

    An applet must have either java.applet.Applet or javax.swing.JApplet as its parent class.

    A standalone application must contain a method with the following signature:public static void main(String []x)

    In general, a GUI-based application must have a window container serving as the user interfaceand a container to hold/glue user interface objects. Hence, there are two major kinds of

    containers: window-enabled and non-window. A window container cannot be contained inside

    another container; whereas, a non-window container MUST be contained inside another

    container. The java.applet.Applet and javax.swing.JApplet classes are non-window containerclasses and signify that they should be executed in an internet browsers environment/window.

    A standalone application, on the other hand, needs a window container. The java.awt.Frame or

    javax.swing.JFrame is generally used as a window container for a standalone GUI application.

    A GUI program may have many containers. A container can consist of user interfacecomponents and graphic context. Only components can react to user events. Graphic context is

    simply the drawing on a container and is NOT an object.

    It is possible to develop a Java program which can run as a standalone application under a local

    operating system and as an applet via a web browser. In other words, there is no need to developtwo versions of the same programs. The mechanism is to provide the necessary and desired

    applet methods, such as init() and paint(), as well as the main() method as required by a

    standalone application in the same class declaration. The main() method creates an instance of

    the class, adds it to its frame container, and invoke the start() method of the applet object. If theprogram is executed as an applet, the main() method is never invoked at all. The next two

    program examples illustrate how to implement a Java program to run as an applet as well as a

    standalone application.

    TwoFace.java

  • 7/29/2019 Exception Handling.doc

    32/86

    - 32 - Dr. Yaos CS 214 Class Notes #2

    // Java program to run as an applet and an application

    import java.awt.*;import java.applet.Applet;

    public class TwoFace extends Applet

    { String msg = "I am an applet and surfing....";

    public void paint(Graphics g)

    { g.drawString(msg, 60, 20); } // paint

    // The main() method is invoked, when the program runs as an application.// This method is invoked, when the program runs as an application.

    public static void main(String []args)

    {Frame frame1 = new Frame("Application");

    TwoFace x = new TwoFace(); // create an applet objectx.msg = "I am an application and running.....";

    // Add the applet to the frame

    frame1.add(x);

    x.start(); // start s the applet object

    frame1.setVisible(true); // show the frame object

    } // main

    } //TwoFace

    To run the above program as a standalone application, enter:java TwoFace

    To run it as an applet, an HTML file will be needed.

    Run.htm

    To test the above program as an applet, bring up a web browser and then open up Run.htm fromthe browser. You need to make sure that both TwoFace.class and Run.htm files are located in

    the same folder.

    Event Listener Interfaces and Methods

  • 7/29/2019 Exception Handling.doc

    33/86

    - 33 - Dr. Yaos CS 214 Class Notes #2

    Summarized in the following table are the major event interfaces, their listener methods and

    registration (add) methods.

    Interface Listener Method Add Method

    ActionListener actionPerformed (ActionEvent) addActionListener (ActionListener)

    AdjustmentListener adjustValue (ComponentEvent) addAdjustmentListener(AdjustmentListener)

    ComponentListener componentHidden(ComponentEvent)componentMoved(ComponentEvent)

    componentResized(ComponentEvent)

    componentShown(ComponentEvent)

    addComponentListener(ComponentListener)

    ContainerListener componentAdded(ContainerEvent)

    componentRemoved(ContainerEvent)

    addContainerListener

    (ContainerListener)

    FocusListener focusGained(FocusEvent)

    focusLost(FocusEvent)

    addFocusListener

    (FocusListener)ItemListener itemChanged(ItemEvent) addItemListener

    (ItemListener)

    KeyListener keyPressed(KeyEvent)

    keyReleased(KeyEvent)

    keyTyped(KeyEvent)

    addkeyListener

    (KeyListener)

    MouseListener mouseClicked(MouseEvent)

    mouseEntered(MouseEvent)

    mouseExited(MouseEvent)mousePressed(MouseEvent)

    mouseReleased(MouseEvent)

    addMouseListener

    (MouseListener)

    MouseMotionListener

    mouseDragged(MouseEvent)mouseMoved(MouseEvent)

    addMouseMotionListener(MouseMotionListener)

    TextListener textValueChanged(TextEvent) addTextListener

    (TextListener)

    WindowListener windowActivated(WindowEvent)

    windowClosed(WindowEvent)

    windowClosing(WindowEvent)

    windowDeactivated(WindowEvent)windowDeiconified(WindowEvent)

    windowIconified(WindowEvent)

    windowopened(WindowEvent)

    addWindowListener

    (WindowListener)

    Associated with each of the above interfaces, there is a method used to de-register an object fromthe interface. The naming convention for this method is:

    removeInterFaceName(.)

    For example,removeActionListener (ActionListener)

    // DrawLine4.javaimport java.awt.*;

  • 7/29/2019 Exception Handling.doc

    34/86

    - 34 - Dr. Yaos CS 214 Class Notes #2

    import java.applet.Applet;

    import java.awt.event.*;

    public class DrawLine4 extends Applet implements MouseListener, MouseMotionListener{

    final int MAXLINES = 10;Point starts[] = new Point[MAXLINES]; // starting points

    Point ends[] = new Point[MAXLINES]; // ending points

    Point anchor; // start of current linePoint currentpoint; // current end of line

    int currline = 0; // number of lines

    public void init(){ // register event listeners

    addMouseListener(this);

    addMouseMotionListener(this);

    } // init

    // MouseListener listener methodspublic void mouseClicked(MouseEvent e) {}

    public void mouseEntered(MouseEvent e) {}

    public void mouseExited(MouseEvent e) {}public void mousePressed(MouseEvent e) // same as mouseDown in JDK 1.0

    { anchor = new Point(e.getX(),e.getY()); }

    public void mouseReleased(MouseEvent e) // same as mouseUp in JDK 1.0

    { addline(e.getX(),e.getY()); }

    // MouseMotionListener listener methods

    public void mouseDragged(MouseEvent e) // same as mouseDrag in JDK 1.0{

    currentpoint = new Point(e.getX(),e.getY());

    repaint();}

    public void mouseMoved(MouseEvent e) {}

    void addline(int x,int y){

    starts[currline] = anchor;

    ends[currline] = new Point(x,y);++currline;

    currentpoint = null;

    anchor = null;repaint();

    } // addline

    public void paint(Graphics g)

  • 7/29/2019 Exception Handling.doc

    35/86

    - 35 - Dr. Yaos CS 214 Class Notes #2

    {

    // Draw existing lines

    for (int i = 0; i < currline; i++)g.drawLine(starts[i].x, starts[i].y, ends[i].x, ends[i].y);

    // draw current line

    g.setColor(Color.yellow);if (currentpoint != null)

    g.drawLine(anchor.x,anchor.y,

    currentpoint.x,currentpoint.y);}

    }

    Let us use the MouseListener interface as the event listener to capture the mouse click. In this

    program, a click on the mouse causes a blue square be displayed at the mouse clicking point.

    //DrawDot3.java

    // Display a filled square at the mouse pointer when the mouse is pressed.// Using a frame as the container, instead of an applet.

    import java.awt.event.*;

    import java.awt.*;

    public class DrawDot3 extends Frame implements MouseListener, WindowListener{

    private int x, y = 0; // x, y coordinatespublic DrawDot3() // Default constructor

    {

    setTitle("DrawDot3");// Register to the event listeners

    addMouseListener(this);addWindowListener(this);

    } // constructor

    public static void main(String[] args)

    { DrawDot3 x = new DrawDot3();

    x.setSize(250, 250);

    x.setVisible(true);

    }

    // Draw a blue square at the point (x, y)public void paint(Graphics g)

    {

    g.drawString("("+x+", "+y+")", x-5, y-5);

    g.setColor(Color.blue);

  • 7/29/2019 Exception Handling.doc

    36/86

    - 36 - Dr. Yaos CS 214 Class Notes #2

    g.fillRect(x, y, 7, 7);

    } // paint

    // MouseListener listener methods

    // When the mouse is pressed, the mouse pointer location will be stored in (x, y)

    public void mousePressed(MouseEvent e){

    // Get (x, y) coordinates using getX() and getY() methods

    x = e.getX();y = e.getY();

    repaint();

    }

    public void mouseClicked(MouseEvent e) {}

    public void mouseEntered(MouseEvent e) {}

    public void mouseExited(MouseEvent e) {}

    public void mouseReleased(MouseEvent e) {}

    // Listener methods declared in the WindowListener interface

    public void windowClosing(WindowEvent e)

    {setVisible(false); // or dispose();

    System.exit(1);

    } // windowClosing

    public void windowClosed(WindowEvent e) { }

    public void windowDeiconified(WindowEvent e) { }

    public void windowIconified(WindowEvent e) { }public void windowActivated(WindowEvent e) { }

    public void windowDeactivated(WindowEvent e) { }

    public void windowOpened(WindowEvent e) { }

    } // DrawDot3

  • 7/29/2019 Exception Handling.doc

    37/86

    - 37 - Dr. Yaos CS 214 Class Notes #3

    Using MenusThe steps of adding the menu capability are:1. create a menu bar

    2. activate the menu bar

    3. create a menu

    4. add the menu to the menu bar 5. create a menu item

    6. add the menu item to the menu

    The javax.swing package provides classes to support the memnu capability. These class are:

    JMenuBar, JMenu, and JMenuItem. The method setMenuBar() allows javax.swing.JFrame to set

    an active menu bar. One menu bar can be set to active at any given point of time. In order toreact to the click on a menu item event, the ActionListener interface will be used. Hence, a

    menu item works almost identically to a push button (javax.swing.JButton). Each menu and

    menu item is associated with a label. Separators can also be added by calling the method

    addSeparator() of the JMenu class. The Java statements corresponding to the steps listed above

    may look like:1. JMenuBar menuBar = new JMenuBar();

    2. setMenuBar(menuBar); // e.g., new JFrame().setMenuBar(menuBar);3. JMenu menuA = new JMenu(A Menu);

    4. menuBar.add(menuA);

    5. JMenuItem menuItemA = new JMenuItem(Menu Item A);6. menuA.add(menuItemA);

    The following program example, UseMenu.java, shows how menu capabilities can beimplemented in a GUI program. This program also demonstrates how to implement an event

    withdrawal and to activate a specific menu bar.

    // Using JMenuBar, JMenu, and JMenuItem to set up menusimport javax.swing.*;

    import java.awt.event.*;

    public class UseMenu extends JFrame implements ActionListener

    {

    JMenuItem item1, item2, item3, item4, item5, item6;JMenuBar menuBar1, menuBar2;

    public static void main(String []args)

    {UseMenu x = new UseMenu();

    x.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    x.setSize(350, 250);x.setVisible(true);

    } // main

    // constructor

  • 7/29/2019 Exception Handling.doc

    38/86

    - 38 - Dr. Yaos CS 214 Class Notes #3

    public UseMenu()

    {

    setTitle("Using Menus");// Step 1 create menu bar

    menuBar1 = new JMenuBar();

    menuBar2 = new JMenuBar();// Step 2 activate a menu bar

    setJMenuBar(menuBar1);

    // Step 3 create menuJMenu menuA = new JMenu("Menu 1");

    JMenu menuB = new JMenu("Menu 2");

    JMenu menuC = new JMenu("Menu 3");

    // Step 4 add menu to a menu barmenuBar1.add(menuA);

    menuBar1.add(menuB);

    menuBar2.add(menuC);

    // Step 5 create menu itemitem1 = new JMenuItem("ONE");

    item2 = new JMenuItem("2");item3 = new JMenuItem("Switch menu bar");

    item4 = new JMenuItem("Selection #4");

    item5 = new JMenuItem("change size");item6 = new JMenuItem("Exit");

    // Step 6 add menu item to a menu

    menuA.add(item1);

    menuA.addSeparator();menuA.add(item2);

    menuB.add(item3);

    menuB.addSeparator();menuB.add(item4);

    menuB.add(item5);

    menuC.add(item6);// event registrationitem1.addActionListener(this);

    item2.addActionListener(this);

    item3.addActionListener(this);item4.addActionListener(this);

    item5.addActionListener(this);

    item6.addActionListener(this);} // constructor

    public void actionPerformed(ActionEvent e){

    if (e.getSource() == item1)

    setTitle("Menu Item1 selected");

    if (e.getSource() == item2)

  • 7/29/2019 Exception Handling.doc

    39/86

    - 39 - Dr. Yaos CS 214 Class Notes #3

    {

    setTitle("Welcome to Menu Item2");

    item2.removeActionListener(this);}

    if (e.getSource() == item3)

    {setTitle("New menu bar");

    setJMenuBar(menuBar2);

    }if (e.getSource() == item4)

    setTitle("4 is a simple Four");

    if (e.getSource() == item5)

    {setTitle("Give me 5");

    setSize(190, 210);

    }

    if (e.getSource() == item6)System.exit(0);

    repaint();

    } // actionPerformed

    } // UseMenu

  • 7/29/2019 Exception Handling.doc

    40/86

    - 40 - Dr. Yaos CS 214 Class Notes #3

    Advanced Swing FeaturesThe javax.swing package provides many classes to support the development of GUI applications.Classes covered here include JList, JTree, JTable, JEditorPane, JSplitPane, JTabbedPane,

    JDesktopPane, and JInternalFrame.

    javax.swing.JList classConstructors:

    JList();

    JList(ListModel x);JLIst(Object [] x);

    JList(Vector x);

    Methods used in UseJList1.java:

    int getSelectedIndex(); // returns the index of the selected item

    int [] getSelectedIndices(); // returns the indices of the selected items

    Object getSelectedValue(); // returns the selected item as an Object

    Object [] getSelectedValues(); // returns the selected items as an Object arrayvoid set SelectionMode(int m); // sets the mode to be single or multiple selection

    //UseJList1.java

    // Using javax.JList to allow a single selection at a time

    import java.awt.*;import java.awt.event.*;

    import javax.swing.*;

    import javax.swing.event.*;public class UseJList1 extends JFrame

    {

    JLabel label;JList myList;String [] msg = {"BMW","Vacation","Free lunch","Try again","Try harder"};

    public static void main(String []args)

    {UseJList1 x = new UseJList1();

    x.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    x.setSize(250, 250);x.setVisible(true);

    } // main

    public UseJList1() // constructor{

    setTitle("UseJList1");

    String [] s = new String[5];for (int k=0; k < s.length; ++k)

    s[k] = "Try Me" + k;

    myList = new JList(s); // create a JList object from a String array// Allow only single selection

  • 7/29/2019 Exception Handling.doc

    41/86

    - 41 - Dr. Yaos CS 214 Class Notes #3

    myList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    JScrollPane sp = new JScrollPane(myList); // adding scrolling capability

    JPanel p = new JPanel();p.add(sp);

    // Event registration and handling

    // The ListSelectionListener interface handles a click on a list item. myList.addListSelectionListener(new ListSelectionListener(){

    public void valueChanged(ListSelectionEvent e){

    String value = (String) myList.getSelectedValue();

    label.setText(value + " says: " + msg[myList.getSelectedIndex()]);

    }});

    getContentPane().add(p, BorderLayout.SOUTH);

    label = new JLabel("Try Your Luck");

    getContentPane().add(label, BorderLayout.NORTH);} // constructor

    } // UseJList1

    // FileList.java

    // Using javax.Jlist to show the current directory contentsimport java.io.*;

    import java.awt.*;

    import java.awt.event.*;

    import javax.swing.*;import javax.swing.event.*;

    public class FileList extends JFrame {

    JLabel label;JList myList;

    JTextField fileType;

    String []dirList;public static void main(String []args) {

    FileList x = new FileList();

    x.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    x.setSize(250, 250);x.setVisible(true);

    } // main

    public FileList(){// constructorsetTitle("FileList");

    try { File mypath = new File("."); // current directory

    dirList = mypath.list(); // get the file list} catch(Exception e) { e.printStackTrace(); System.exit(2); }

    JPanel p = new JPanel();

    fileType = new JTextField(20);

    p.add(fileType);

  • 7/29/2019 Exception Handling.doc

    42/86

    - 42 - Dr. Yaos CS 214 Class Notes #3

    myList = new JList(dirList); // create a JList object

    myList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    JScrollPane sp = new JScrollPane(myList); // adding scrolling capabilityp.add(sp);

    getContentPane().add(p, BorderLayout.SOUTH);

    label = new JLabel("");getContentPane().add(label, BorderLayout.NORTH);

    // event registration and handling

    // The ListSelectionListener interface handles a click on a list item.myList.addListSelectionListener(new ListSelectionListener() { public void

    valueChanged(ListSelectionEvent e) { String v = (String) myList.getSelectedValue();

    label.setText(v);

    if ((new File(v)).isFile()) fileType.setText(v + " is a file");if ((new File(v)).isDirectory()) fileType.setText(v + " is a directory");

    } });

    } // constructor

    } // FileList

    The next program retrieves database records and displays them in a JList.

    // UseJList2.java// Using javax.JList to display database records

    import java.awt.*;

    import java.awt.event.*;

    import javax.swing.*;import javax.swing.event.*;

    import java.sql.*;

    import java.util.*;

    public class UseJList2 extends JFrame

    {JLabel label;

    JList myList;

    Vector lName; // store last names

    Object []fName; // hold first namespublic static void main(String []args)

    {

    UseJList2 x = new UseJList2();x.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    x.setSize(350, 250);

    x.setVisible(true);} // main

    public UseJList2() // constructor

    {

  • 7/29/2019 Exception Handling.doc

    43/86

    - 43 - Dr. Yaos CS 214 Class Notes #3

    setTitle("UseJList2");

    lName = new Vector(); // store last names

    try { getRecord(); // Retrieve database records

    } catch(Exception e) { System.err.println(e); }

    myList = new JList(lName); // create a JList object based on last names// Allow only single selection

    myList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    JScrollPane sp = new JScrollPane(myList); // adding scrolling capabilityJPanel p = new JPanel();

    p.add(sp);

    // event registration and handling

    // The ListSelectionListener interface handles a click on a list item.

    myList.addListSelectionListener (new ListSelectionListener()

    {

    public void valueChanged(ListSelectionEvent e)

    {label.setText(fName[myList.getSelectedIndex()].toString());

    }});

    getContentPane().add(p, BorderLayout.SOUTH);

    label = new JLabel(); // used to show the first namegetContentPane().add(label, BorderLayout.NORTH);

    } // constructor

    public void getRecord() throws Exception

    {

    // The name of the JDBC driverString driverName = "sun.jdbc.odbc.JdbcOdbcDriver";

    // JDBC connection URL

    String connectionURL = "jdbc:odbc:SimpleDB";Connection con = null; // JDBC Connection object

    Statement stmt = null; // JDBC Statement object

    // SQL statement used to retrieve records

    String sqlStatement = "SELECT LastName, FirstName FROM PEOPLE";ResultSet rs = null; // JDBC ResultSet object

    try

    {Class.forName(driverName).newInstance(); // Load the driver

    // Establish a database connection

    con = DriverManager.getConnection(connectionURL);stmt = con.createStatement(); // Create the SQL statement

    rs = stmt.executeQuery(sqlStatement); // Execute the query

    Vector v = new Vector();

    // Step through the entire ResultSet

  • 7/29/2019 Exception Handling.doc

    44/86

    - 44 - Dr. Yaos CS 214 Class Notes #3

    while (rs.next())

    {

    lName.addElement(rs.getString(1)); // get the last name v.addElement(rs.getString(2)); // get the first name

    } // while

    fName = v.toArray(); // convert the first names into an array} // try

    catch (Exception e) { System.err.println(e); }

    finally{ // Cleaning up

    if (rs != null) rs.close();

    if (stmt != null) stmt.close();

    if (con != null) con.close();} // finally

    } // getRecord

    } // UseJList2

    javax.swing.JTree class

    Constructors:JTree();

    JTree(Hashtable x); // create a tree object based on a Hashtable

    JTree(TreeNode x); // create a tree object based on a TreeNode

    JTree(TreeNode x, boolean leaf); // true, if child node is a leaf nodeJTree(TreeModel x); // create a tree object based on a TreeModel

    JTree(Object []x); // create a tree object based on an Object arrayJTree(Vector x); // create a tree object based on a Vector

    // UseJTree1.java

    // Using javax.JTree to create and show a list of stringsimport java.awt.*;

    import java.awt.event.*;

    import javax.swing.*;import javax.swing.event.*;

    public class UseJTree1 extends JFrame

    {

    JTree myTree;public static void main(String []args)

    {

    UseJTree1 x = new UseJTree1();x.setSize(180, 200);

    x.setVisible(true);

    x.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);} // main

  • 7/29/2019 Exception Handling.doc

    45/86

    - 45 - Dr. Yaos CS 214 Class Notes #3

    public UseJTree1() // constructor

    {setTitle("UseJTree1");

    String []s = new String[10];

    for (int k=0; k < s.length; ++k) s[k] = "Hello " + k;myTree = new JTree(s); // create a JTree object based on a String array

    JScrollPane sp = new JScrollPane(myTree); // adding scrolling capability

    getContentPane().add(sp);} // constructor

    } // UseJTree1

    The above program simply creates a JTree object to show a list of strings. No event associated

    statements were added. Each node in the tree is a leaf node and does not any child nodes. Thus,

    the icons shown in the above figure are leaf icons. The DefaultMutableTreeNode class

    represents a node in a tree component and is one of many tree node related classes facilitated bythejavax.swing.tree package. Thus, a tree node can be created by call the constructor:

    DefaultMutableTreeNode(Object x);

    // UseJTree2.javaimport java.awt.event.*;

    import javax.swing.*;

    import javax.swing.tree.*;

    import javax.swing.event.*;public class UseJTree2 extends JFrame {

    JTree myTree;

    public static void main(String []args) {

    UseJTree2 x = new UseJTree2();

    x.setSize(250, 200);x.setVisible(true);

    x.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    } // main

    public UseJTree2() // constructor

    {

    setTitle("UseJTree2");String []s = {"Hello", "Howdy", "Hey", "Hi"};

    DefaultMutableTreeNode temp;

    DefaultMutableTreeNode myRoot = new DefaultMutableTreeNode("Top");for (int k=0; k < s.length; ++k)

    {

    temp = new DefaultMutableTreeNode(s[k]);

    // add 4 child nodes

  • 7/29/2019 Exception Handling.doc

    46/86

    - 46 - Dr. Yaos CS 214 Class Notes #3

    for (int n=1; n

  • 7/29/2019 Exception Handling.doc

    47/86

    - 47 - Dr. Yaos CS 214 Class Notes #3

    DefaultMutableTreeNode myRoot = new DefaultMutableTreeNode("Top");

    for (int k=0; k < s.length; ++k)

    {temp = new DefaultMutableTreeNode(s[k]);

    // add 4 child nodes

    for (int n=1; n

  • 7/29/2019 Exception Handling.doc

    48/86

    - 48 - Dr. Yaos CS 214 Class Notes #3

    DefaultMutableTreeNode myRoot;

    DefaultTreeModel treeMod; // a tree model

    public static void main(String []args) {UseJTree4 x = new UseJTree4();

    x.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    x.setSize(250, 200);x.setVisible(true);

    } // main

    public UseJTree4() // constructor

    {

    setTitle("UseJTree4");

    String []s = {"Hello", "Howdy", "Hey", "Hi"};DefaultMutableTreeNode temp;

    myRoot = new DefaultMutableTreeNode("Top");

    for (int k=0; k < s.length; ++k)

    {temp = new DefaultMutableTreeNode(s[k]);

    for (int n=1; n

  • 7/29/2019 Exception Handling.doc

    49/86

    - 49 - Dr. Yaos CS 214 Class Notes #3

    public void actionPerformed(ActionEvent e)

    { // 1. Asking the tree which node was selected

    DefaultMutableTreeNode selectedNode =

    (DefaultMutableTreeNode) myTree.getLastSelectedPathComponent();

    if (selectedNode == null) return; // no node was selected

    // 2. Asking the selected node who is its parentDefaultMutableTreeNode parent =

    (DefaultMutableTreeNode) selectedNode.getParent();

    if (parent == null)return; // There can be only one rootnode

    // create a new tree node

    DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("New");

    // 3. Asking the parent node for the index of the selected node

    int selectedIndex = parent.getIndex(selectedNode);

    // 4. Adding the new node to the tree model at the same level

    treeMod.insertNodeInto(newNode, parent, selectedIndex + 1);

    // 5. Builds an array of nodes for a specific node and upTreeNode[] nodes = treeMod.getPathToRoot(newNode);

    TreePath path = new TreePath(nodes); // create a new tree path// 6. Redisplays the tree nodes to show the newly added node

    myTree.scrollPathToVisible(path);

    }});

    childlevel.addActionListener (new ActionListener()

    {

    public void actionPerformed(ActionEvent e){ // get the selected node

    DefaultMutableTreeNode selectedNode =

    (DefaultMutableTreeNode) myTree.getLastSelectedPathComponent();

    if (selectedNode == null)

    return; // no node was selected

    // create a new tree node

    DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("New");

    // 7. Adding the new node to the tree model at the lower leveltreeMod.insertNodeInto(newNode, selectedNode, selectedNode.getChildCount());

    TreeNode[] nodes = treeMod.getPathToRoot(newNode);

    TreePath path = new TreePath(nodes);

    myTree.scrollPathToVisible(path); // display the new node

    }});

    delete.addActionListener(new ActionListener(){

    public void actionPerformed(ActionEvent e)

    { // get the selected node

    DefaultMutableTreeNode selectedNode =

  • 7/29/2019 Exception Handling.doc

    50/86

    - 50 - Dr. Yaos CS 214 Class Notes #3

    (DefaultMutableTreeNode) myTree.getLastSelectedPathComponent();

    if (selectedNode != null && selectedNode.getParent() != null)

    // 8. remove a node from the tree model

    treeMod.removeNodeFromParent(selectedNode);

    }

    });} // addButton} // UseJTree4

    Let us take a closer look at the methods and classes used in the preceding example,

    UseJTree4.java. In addition to the DefaultTreeModel class, this program also uses the

    javax.swing.tree.TreePath class which represents a path to a node in a tree and is used toconstruct a path from an array of tree nodes in order to uniquely identifying the path from the

    root of the tree to a specific node. The following constructor is used to instantiate an object from

    the DefaultTreeModel class:

    DefaultTreeModel(TreeNode x); // Creates a tree in which any node can have child nodes

    // where x represents the root for a set of tree nodesOther methods used in UseJTree4.java include:

    1. Object getLastSelectedPathComponent(); // JTree classReturns the selected node

    2. TreeNode getParent(); // DefaultMutableTreeNode class

    3. int getIndex(TreeNode ChildNode); // DefaultMutableTreeNode class

    Returns the index of the specified child node.

    4. void insertNodeInto(TreeNode x, TreeNode parent, int where); // DefaultTreeModelclass

    Adds the newnode x as a child node of parent node at the index where.

    5. TreeNode [] getPathtoRoot(TreeNode x); // DefaultTreeModel class

    Returns an array of tree nodes from the immediate parent of a specific node up to and

    including the root node. The last element in the returned array is the node.

    6. void scrollPathToVisible(TreePath path); // JTree class

    Displays tree nodes. The JTree object must be contained in a JScrollPane container.

    7. int getChildCount(); // DefaultMutableTreeNode class

    Returns the number of children of the node.

    8. void removeNodeFromParent(MutableTreeNode x); // DefaultTreeModel class

    Removes a child node from the current node

    Tree TraversalThejavax.swing.tree.DefaultMutableTreeNode class provides four tree traversal methods:

    Enumeration breadthFirstEnumeration();

  • 7/29/2019 Exception Handling.doc

    51/86

    - 51 - Dr. Yaos CS 214 Class Notes #3

    Enumeration depthFirstEnumeration();

    Enumeration preorderFirstEnumeration(); // same as depthFirst

    Enumeration postorderFirstEnumeration(); // reverse of preorder

    // UseJTree5.java

    // Visiting tree nodes in two different ways: breadth first and depth first.import java.awt.*;

    import java.awt.event.*;

    import javax.swing.*;import javax.swing.tree.*;

    import javax.swing.event.*;

    import java.util.*;public class UseJTree5 extends JFrame {

    JTree myTree;

    DefaultMutableTreeNode myRoot;

    DefaultTreeModel treeMod;

    JScrollPane sp2;public static void main(String []args) {

    UseJTree5 x = new UseJTree5();x.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    x.setSize(250, 200);

    x.setVisible(true);} // main

    public UseJTree5() // constructor

    {setTitle("UseJTree5");

    String []s = {"Hello", "Howdy", "Hey", "Hi"};DefaultMutableTreeNode temp;myRoot = new DefaultMutableTreeNode("Top");

    for (int k=0; k < s.length; ++k) {

    temp = new DefaultMutableTreeNode(s[k]);for (int n=1; n

  • 7/29/2019 Exception Handling.doc

    52/86

    - 52 - Dr. Yaos CS 214 Class Notes #3

    x = (DefaultMutableTreeNode) nodeRec.nextElement();

    v.addElement(x.toString());

    }JList nodeList = new JList(v);

    getContentPane().add(new JScrollPane(nodeList));

    v = new Vector();

    nodeRec = myRoot.depthFirstEnumeration(); // depth firstwhile (nodeRec.hasMoreElements()) {

    x = (DefaultMutableTreeNode) nodeRec.nextElement();

    v.addElement(x.toString());

    }

    nodeList = new JList(v);getContentPane().add(new JScrollPane(nodeList));

    } // constructor

    } // UseJTree5

    The next program demonstrates how to visit tree nodes in the original order in which they are

    added to the tree. A recursive function is used to visit each node at all levels of a tree.

    // UseJTree6.java// Showing the sub-tree of a selected node

    import java.awt.*;import java.awt.event.*;

    import javax.swing.*;

    import javax.swing.tree.*;import javax.swing.event.*;

    import java.io.*;

    import java.util.*;

    public class UseJTree6 extends JFrame

    {

    JTree myTree;DefaultMutableTreeNode myRoot;

    DefaultTreeModel treeMod;

    JTextArea outbox;

    public static void main(String []args)

    {UseJTree6 x = new UseJTree6();

    x.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    x.setSize(400, 300);

    x.setVisible(true);

  • 7/29/2019 Exception Handling.doc

    53/86

    - 53 - Dr. Yaos CS 214 Class Notes #3

    } // main

    public UseJTree6() // constructor{

    setTitle("UseJTree6");

    String []s = {"Hello", "Howdy", "Hey", "Hi"};DefaultMutableTreeNode temp;

    myRoot = new DefaultMutableTreeNode("Top");

    for (int k=0; k < s.length; ++k) {temp = new DefaultMutableTreeNode(s[k]);

    for (int n=1; n

  • 7/29/2019 Exception Handling.doc

    54/86

    - 54 - Dr. Yaos CS 214 Class Notes #3

    });

    } // addButton

    // print each tree node recursively

    void printNode(DefaultMutableTreeNode node)

    {int k = node.getChildCount(); // Get child count

    if (k == 0) // This is a leaf node; recursion stops here

    {outbox.setText(outbox.getText() + node.toString() + "\n"); // print the leaf

    return;

    }

    // print a root node and the number of child nodes it has outbox.setText(outbox.getText() + node.toString() + " " + k + "\n");

    // Asking each child node to print itself

    for (int n=0; n < k; ++n)

    printNode((DefaultMutableTreeNode) node.getChildAt(n)); // recursive call} // printNode

    } // UseJTree6

    // UseJTree7.java

    // Adding, removing, showing, and saving tree nodesimport java.awt.*;

    import java.awt.event.*;

    import javax.swing.*;import javax.swing.tree.*;import javax.swing.event.*;

    import java.io.*;

    public class UseJTree7 extends JFrame {JTree myTree;

    DefaultMutableTreeNode myRoot;

    DefaultTreeModel treeMod;JTextArea outbox;

    PrintWriter outfile;

    public static void main(String []args) {UseJTree7 x = new UseJTree7();

    x.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    x.setSize(500, 300);x.setVisible(true);

    } // main

    public UseJTree7() // constructor{

  • 7/29/2019 Exception Handling.doc

    55/86

    - 55 - Dr. Yaos CS 214 Class Notes #3

    setTitle("UseJTree7");

    String []s = {"Hello", "Howdy", "Hey", "Hi"};

    DefaultMutableTreeNode temp;myRoot = new DefaultMutableTreeNode("Top");

    for (int k=0; k < s.length; ++k)

    {temp = new DefaultMutableTreeNode(s[k]);

    // add 3 child nodes

    for (int n=1; n

  • 7/29/2019 Exception Handling.doc

    56/86

    - 56 - Dr. Yaos CS 214 Class Notes #3

    DefaultMutableTreeNode parent =

    (DefaultMutableTreeNode) selectedNode.getParent();

    if (parent == null) return;DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("New");

    int selectedIndex = parent.getIndex(selectedNode);

    // adding the new node to the top level nodetreeMod.insertNodeInto(newNode, parent, selectedIndex + 1);

    // display the new node

    TreeNode[] nodes = treeMod.getPathToRoot(newNode);TreePath path = new TreePath(nodes);

    myTree.scrollPathToVisible(path);

    }

    });

    childlevel.addActionListener(new ActionListener()

    {

    public void actionPerformed(ActionEvent e){

    DefaultMutableTreeNode selectedNode =(DefaultMutableTreeNode) myTree.getLastSelectedPathComponent();

    if (selectedNode == null) return;

    DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("New");// add the new node

    treeMod.insertNodeInto(newNode, selectedNode, selectedNode.getChildCount());

    // display the new node

    TreeNode[] nodes = treeMod.getPathToRoot(newNode);TreePath path = new TreePath(nodes);

    myTree.scrollPathToVisible(pa