Kinesia Online Course
Object Oriented Programming
Kinesia LLC, 2003
    1. A Little Taste of Java
    2. Abstraction and Modeling
    3. Objects and Classes
    4. Object Interactions
    5. UML and Relationships between Objects
    6. Collection of Objects
    7. Some Final Concepts
    8. Object Modeling and Use Cases
    9. Modeling of Dynamic Behavaior and Sequence Diagrams
    10. A Deeper Look at Java
    11. Java Layout
    12. Java Events
    
    
    
    Java Events
    1. Mouse Events

      Two categories:

    2. mouse events

    3. mouse motion events
    4. Mouse EventDescription
      mouse pressed the mouse button is pressed
      mouse released       the mouse button is released
      mouse clicked       the mouse button is pressed down and released without moving
      the mouse in between
      mouse entered       the mouse pointer is moved onto ( over ) a component
      mouse exited       the mouse pointer is moved off a component

      Mouse Motion EventDescription
      mouse moved the mouse is moving
      mouse dragged       the mouse is moved while the mouse button is being pressed down

      //********************************************************************
      //  RubberLines.java       Author: Lewis/Loftus
      //
      //  Demonstrates mouse events and rubberbanding.
      //********************************************************************
      
      import javax.swing.JFrame;
      
      public class RubberLines
      {
         //-----------------------------------------------------------------
         //  Creates and displays the application frame.
         //-----------------------------------------------------------------
         public static void main (String[] args)
         {
            JFrame frame = new JFrame ("Rubber Lines");
            frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
      
            frame.getContentPane().add (new RubberLinesPanel());
      
            frame.pack();
            frame.setVisible(true);
         }
      }
      //********************************************************************
      //  RubberLinesPanel.java       Author: Lewis/Loftus
      //
      //  Represents the primary drawing panel for the RubberLines program.
      //********************************************************************
      
      import javax.swing.JPanel;
      import java.awt.*;
      import java.awt.event.*;
      
      public class RubberLinesPanel extends JPanel
      {
         private Point point1 = null, point2 = null;
      
         //-----------------------------------------------------------------
         //  Constructor: Sets up this panel to listen for mouse events.
         //-----------------------------------------------------------------
         public RubberLinesPanel()
         {
            LineListener listener = new LineListener();
            addMouseListener (listener);
            addMouseMotionListener (listener);
      
            setBackground (Color.black);
            setPreferredSize (new Dimension(400, 200));
         }
      
         //-----------------------------------------------------------------
         //  Draws the current line from the intial mouse-pressed point to
         //  the current position of the mouse.
         //-----------------------------------------------------------------
         public void paintComponent (Graphics page)
         {
            super.paintComponent (page);
      
            page.setColor (Color.yellow);
            if (point1 != null && point2 != null)
               page.drawLine (point1.x, point1.y, point2.x, point2.y);
         }
      
         //*****************************************************************
         //  Represents the listener for all mouse events.
         //*****************************************************************
         private class LineListener implements MouseListener,
                                               MouseMotionListener
         {
            //--------------------------------------------------------------
            //  Captures the initial position at which the mouse button is
            //  pressed.
            //--------------------------------------------------------------
            public void mousePressed (MouseEvent event)
            {
               point1 = event.getPoint();
            }
      
            //--------------------------------------------------------------
            //  Gets the current position of the mouse as it is dragged and
            //  redraws the line to create the rubberband effect.
            //--------------------------------------------------------------
            public void mouseDragged (MouseEvent event)
            {
               point2 = event.getPoint();
               repaint();
            }
      
            //--------------------------------------------------------------
            //  Provide empty definitions for unused event methods.
            //--------------------------------------------------------------
            public void mouseClicked (MouseEvent event) {}
            public void mouseReleased (MouseEvent event) {}
            public void mouseEntered (MouseEvent event) {}
            public void mouseExited (MouseEvent event) {}
            public void mouseMoved (MouseEvent event) {}
         }
      }
        

    5. Key Events

    6. A key event is generated when a key is pressed.

    7. respond immediately, no need to wait for Enter
    8. //********************************************************************
      //  Direction.java       Author: Lewis/Loftus
      //
      //  Demonstrates key events.
      //********************************************************************
      
      import javax.swing.JFrame;
      
      public class Direction
      {
         //-----------------------------------------------------------------
         //  Creates and displays the application frame.
         //-----------------------------------------------------------------
         public static void main (String[] args)
         {
            JFrame frame = new JFrame ("Direction");
            frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
      
            frame.getContentPane().add (new DirectionPanel());
      
            frame.pack();
            frame.setVisible(true);
         }
      }
      //********************************************************************
      //  DirectionPanel.java       Author: Lewis/Loftus
      //
      //  Represents the primary display panel for the Direction program.
      //********************************************************************
      
      import javax.swing.*;
      import java.awt.*;
      import java.awt.event.*;
      
      public class DirectionPanel extends JPanel
      {
         private final int WIDTH = 300, HEIGHT = 200;
         private final int JUMP = 10;  // increment for image movement
      
         private final int IMAGE_SIZE = 31;
      
         private ImageIcon up, down, right, left, currentImage;
         private int x, y;
      
         //-----------------------------------------------------------------
         //  Constructor: Sets up this panel and loads the images.
         //-----------------------------------------------------------------
         public DirectionPanel()
         {
            addKeyListener (new DirectionListener());
      
            x = WIDTH / 2;
            y = HEIGHT / 2;
      
            up = new ImageIcon ("arrowUp.gif");
            down = new ImageIcon ("arrowDown.gif");
            left = new ImageIcon ("arrowLeft.gif");
            right = new ImageIcon ("arrowRight.gif");
      
            currentImage = right;
      
            setBackground (Color.black);
            setPreferredSize (new Dimension(WIDTH, HEIGHT));
            setFocusable(true);
         }
      
         //-----------------------------------------------------------------
         //  Draws the image in the current location.
         //-----------------------------------------------------------------
         public void paintComponent (Graphics page)
         {
            super.paintComponent (page);
            currentImage.paintIcon (this, page, x, y);
         }
      
         //*****************************************************************
         //  Represents the listener for keyboard activity.
         //*****************************************************************
         private class DirectionListener implements KeyListener
         {
            //--------------------------------------------------------------
            //  Responds to the user pressing arrow keys by adjusting the
            //  image and image location accordingly.
            //--------------------------------------------------------------
            public void keyPressed (KeyEvent event)
            {
               switch (event.getKeyCode())
               {
                  case KeyEvent.VK_UP:
                     currentImage = up;
                     y -= JUMP;
                     break;
                  case KeyEvent.VK_DOWN:
                     currentImage = down;
                     y += JUMP;
                     break;
                  case KeyEvent.VK_LEFT:
                     currentImage = left;
                     x -= JUMP;
                     break;
                  case KeyEvent.VK_RIGHT:
                     currentImage = right;
                     x += JUMP;
                     break;
               }
      
               repaint();
            }
      
            //--------------------------------------------------------------
            //  Provide empty definitions for unused event methods.
            //--------------------------------------------------------------
            public void keyTyped (KeyEvent event) {}
            public void keyReleased (KeyEvent event) {}
         }
      }
        

    9. Extending Adapter Classes

      In the RubberLines program example, the listener interface contains event methods that are not relevant to a particular program and we provide empty definitions to satisfy the interface definitions.

      A alternative technique for creating a listener class is to extend an event adapter class. Each listener interface that contains more than one method has a corresponding adapter class that already contains empty definitions for all of the methods in the interface.

      //********************************************************************
      //  OffCenter.java       Author: Lewis/Loftus
      //
      //  Demonstrates the use of an event adatpter class.
      //********************************************************************
      
      import javax.swing.*;
      
      public class OffCenter
      {
         //-----------------------------------------------------------------
         //  Creates the main frame of the program.
         //-----------------------------------------------------------------
         public static void main (String[] args)
         {
            JFrame frame = new JFrame ("Off Center");
            frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
      
            frame.getContentPane().add(new OffCenterPanel());
            frame.pack();
            frame.setVisible(true);
         }
      }
      //********************************************************************
      //  OffCenterPanel.java       Author: Lewis/Loftus
      //
      //  Represents the primary drawing panel for the OffCenter program.
      //********************************************************************
      
      import java.awt.*;
      import java.awt.event.*;
      import java.text.DecimalFormat;
      import javax.swing.*;
      
      public class OffCenterPanel extends JPanel
      {
         private final int WIDTH=300, HEIGHT=300;
      
         private DecimalFormat fmt;
         private Point current;
         private int centerX, centerY;
         private double length;
      
         //-----------------------------------------------------------------
         //  Constructor: Sets up the panel and necessary data.
         //-----------------------------------------------------------------
         public OffCenterPanel()
         {
            addMouseListener (new OffCenterListener());
      
            centerX = WIDTH / 2;
            centerY = HEIGHT / 2;
      
            fmt = new DecimalFormat ("0.##");
      
            setPreferredSize (new Dimension(WIDTH, HEIGHT));
            setBackground (Color.yellow);
         }
      
         //-----------------------------------------------------------------
         //  Draws a line from the mouse pointer to the center point of
         //  the applet and displays the distance.
         //-----------------------------------------------------------------
         public void paintComponent (Graphics page)
         {
            super.paintComponent (page);
      
            page.setColor (Color.black);
            page.drawOval (centerX-3, centerY-3, 6, 6);
      
            if (current != null)
            {
               page.drawLine (current.x, current.y, centerX, centerY);
               page.drawString ("Distance: " + fmt.format(length), 10, 15);
            }
         }
      
         //*****************************************************************
         //  Represents the listener for mouse events. Demonstrates the
         //  ability to extend an adaptor class.
         //*****************************************************************
         private class OffCenterListener extends MouseAdapter
         {
            //--------------------------------------------------------------
            //  Computes the distance from the mouse pointer to the center
            //  point of the applet.
            //--------------------------------------------------------------
            public void mouseClicked (MouseEvent event)
            {
               current = event.getPoint();
               length = Math.sqrt(Math.pow((current.x-centerX), 2) + 
                                  Math.pow((current.y-centerY), 2));
               repaint();
            }
         }
      }
        

    10. The Timer Class

    11. A timer object, created from the Timer class of the Swing package can be regarded as a GUI component except that it does not have a visual representation that appears on screen.

    12. A timer object generates an action event at regular intervals
    13. //********************************************************************
      //  Rebound.java       Author: Lewis/Loftus
      //
      //  Demonstrates an animation and the use of the Timer class.
      //********************************************************************
      
      import java.awt.*;
      import java.awt.event.*;
      import javax.swing.*;
      
      public class Rebound
      {
         //-----------------------------------------------------------------
         //  Displays the main frame of the program.
         //-----------------------------------------------------------------
         public static void main (String[] args)
         {
            JFrame frame = new JFrame ("Rebound");
            frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
      
            frame.getContentPane().add(new ReboundPanel());
            frame.pack();
            frame.setVisible(true);
         }
      }
      //********************************************************************
      //  ReboundPanel.java       Author: Lewis/Loftus
      //
      //  Represents the primary panel for the Rebound program.
      //********************************************************************
      
      import java.awt.*;
      import java.awt.event.*;
      import javax.swing.*;
      
      public class ReboundPanel extends JPanel
      {
         private final int WIDTH = 300, HEIGHT = 100;
         private final int DELAY = 20, IMAGE_SIZE = 35;
      
         private ImageIcon image;
         private Timer timer;
         private int x, y, moveX, moveY;
      
         //-----------------------------------------------------------------
         //  Sets up the panel, including the timer for the animation.
         //-----------------------------------------------------------------
         public ReboundPanel()
         {
            timer = new Timer(DELAY, new ReboundListener());
      
            image = new ImageIcon ("happyFace.gif");
      
            x = 0;
            y = 40;
            moveX = moveY = 3;
      
            setPreferredSize (new Dimension(WIDTH, HEIGHT));
            setBackground (Color.black);
            timer.start();
         }
      
         //-----------------------------------------------------------------
         //  Draws the image in the current location.
         //-----------------------------------------------------------------
         public void paintComponent (Graphics page)
         {
            super.paintComponent (page);
            image.paintIcon (this, page, x, y);
         }
      
         //*****************************************************************
         //  Represents the action listener for the timer.
         //*****************************************************************
         private class ReboundListener implements ActionListener
         {
            //--------------------------------------------------------------
            //  Updates the position of the image and possibly the direction
            //  of movement whenever the timer fires an action event.
            //--------------------------------------------------------------
            public void actionPerformed (ActionEvent event)
            {
               x += moveX;
               y += moveY;
      
               if (x <= 0 || x >= WIDTH-IMAGE_SIZE)
                  moveX = moveX * -1;
      
               if (y <= 0 || y >= HEIGHT-IMAGE_SIZE)
                  moveY = moveY * -1;
          
               repaint();
            }
         }
      }
        

    14. Event Processing

      Event processing in a Java GUI uses polymorphism to allow a method written years ago to take a parameter whose class was just written.

      For example addActionListener() accepts a parameter of type ActionListener(), the interface. Instead of accepting a parameter of only one object type, the addActionListener() method can accept any object of any class that implements the ActionListener() interface.

    15. File Choosers

       import javax.swing.*;
      import java.awt.*;
      import java.awt.event.*;
      import java.io.*;
      
      /**
        * Demonstrate the use of a JFileChooser to open and
        * save files. The chooser filers for *.java files. Opening
        * the file results in the text fillig a JTextArea component.
        * The text can be modified and saved to a new file.
      
      
      **/
      public class FileChooseApp extends JFrame
             implements ActionListener
      {
      
        JMenuItem fMenuOpen = null;
        JMenuItem fMenuSave  = null;
        JMenuItem fMenuClose = null;
      
        JTextArea fTextArea;
      
        JavaFilter fJavaFilter = new JavaFilter ();
        File fFile = new File ("default.java");
      
        /** Create a frame with JTextArea and a menubar
          * with a "File" dropdown menu.
         **/
        FileChooseApp (String title) {
          super (title);
      
          Container content_pane = getContentPane ();
      
          // Create a user interface.
          content_pane.setLayout ( new BorderLayout () );
          fTextArea = new JTextArea ("");
      
          content_pane.add ( fTextArea, "Center");
      
      
          // Use the helper method makeMenuItem
          // for making the menu items and registering
          // their listener.
          JMenu m = new JMenu ("File");
      
          // Modify task names to something relevant to
          // the particular program.
          m.add (fMenuOpen  = makeMenuItem ("Open"));
          m.add (fMenuOpen  = makeMenuItem ("Save"));
          m.add (fMenuClose = makeMenuItem ("Quit"));
      
          JMenuBar mb = new JMenuBar ();
          mb.add (m);
      
          setJMenuBar (mb);
          setSize (400,400);
        } // ctor
      
        /** Process events from the chooser. **/
        public void actionPerformed ( ActionEvent e ) {
          boolean status = false;
      
          String command = e.getActionCommand ();
          if  (command.equals ("Open")) {
          // Open a file
          status = openFile ();
          if (!status)
              JOptionPane.showMessageDialog (
                null,
                "Error opening file!", "File Open Error",
                JOptionPane.ERROR_MESSAGE
              );
      
          } else if (command.equals ("Save")) {
              // Save a file
              status = saveFile ();
              if (!status)
                  JOptionPane.showMessageDialog (
                    null,
                    "IO error in saving file!!", "File Save Error",
                    JOptionPane.ERROR_MESSAGE
                  );
      
          } else if (command.equals ("Quit") ) {
              dispose ();
          }
        } // actionPerformed
      
        /** This "helper method" makes a menu item and then
          * registers this object as a listener to it.
         **/
        private JMenuItem makeMenuItem (String name) {
          JMenuItem m = new JMenuItem (name);
          m.addActionListener (this);
          return m;
        } // makeMenuItem
      
        /**
          * Use a JFileChooser in Open mode to select files
          * to open. Use a filter for FileFilter subclass to select
          * for *.java files. If a file is selected then read the
          * file and place the string into the textarea.
         **/
        boolean openFile () {
      
            JFileChooser fc = new JFileChooser ();
            fc.setDialogTitle ("Open File");
      
            // Choose only files, not directories
            fc.setFileSelectionMode ( JFileChooser.FILES_ONLY);
      
            // Start in current directory
            fc.setCurrentDirectory (new File ("."));
      
            // Set filter for Java source files.
            fc.setFileFilter (fJavaFilter);
      
            // Now open chooser
            int result = fc.showOpenDialog (this);
      
            if (result == JFileChooser.CANCEL_OPTION) {
                return true;
            } else if (result == JFileChooser.APPROVE_OPTION) {
      
                fFile = fc.getSelectedFile ();
                // Invoke the readFile method in this class
                String file_string = readFile (fFile);
      
                if (file_string != null)
                    fTextArea.setText (file_string);
                else
                    return false;
            } else {
                return false;
            }
            return true;
         } // openFile
      
      
        /**
          * Use a JFileChooser in Save mode to select files
          * to open. Use a filter for FileFilter subclass to select
          * for "*.java" files. If a file is selected, then write the
          * the string from the textarea into it.
         **/
         boolean saveFile () {
           File file = null;
           JFileChooser fc = new JFileChooser ();
      
           // Start in current directory
           fc.setCurrentDirectory (new File ("."));
      
           // Set filter for Java source files.
           fc.setFileFilter (fJavaFilter);
      
           // Set to a default name for save.
           fc.setSelectedFile (fFile);
      
           // Open chooser dialog
           int result = fc.showSaveDialog (this);
      
           if (result == JFileChooser.CANCEL_OPTION) {
               return true;
           } else if (result == JFileChooser.APPROVE_OPTION) {
               fFile = fc.getSelectedFile ();
               if (fFile.exists ()) {
                   int response = JOptionPane.showConfirmDialog (null,
                     "Overwrite existing file?","Confirm Overwrite",
                      JOptionPane.OK_CANCEL_OPTION,
                      JOptionPane.QUESTION_MESSAGE);
                   if (response == JOptionPane.CANCEL_OPTION) return false;
               }
               return writeFile (fFile, fTextArea.getText ());
           } else {
             return false;
           }
        } // saveFile
      
        /** Use a BufferedReader wrapped around a FileReader to read
          * the text data from the given file.
         **/
        public String readFile (File file) {
      
          StringBuffer fileBuffer;
          String fileString=null;
          String line;
      
          try {
            FileReader in = new FileReader (file);
            BufferedReader dis = new BufferedReader (in);
            fileBuffer = new StringBuffer () ;
      
            while ((line = dis.readLine ()) != null) {
                  fileBuffer.append (line + "\n");
            }
      
            in.close ();
            fileString = fileBuffer.toString ();
          }
          catch  (IOException e ) {
            return null;
          }
          return fileString;
        } // readFile
      
      
        /**
          * Use a PrintWriter wrapped around a BufferedWriter, which in turn
          * is wrapped around a FileWriter, to write the string data to the
          * given file.
         **/
        public static boolean writeFile (File file, String dataString) {
          try {
             PrintWriter out =
               new PrintWriter (new BufferedWriter (new FileWriter (file)));
             out.print (dataString);
             out.flush ();
             out.close ();
          }
          catch (IOException e) {
             return false;
          }
          return true;
        } // writeFile
      
        /** Create the framed application and show it. **/
        public static void main (String [] args) {
          // Can pass frame title in command line arguments
          String title="Frame Test";
          if (args.length != 0) title = args[0];
          FileChooseApp f = new FileChooseApp (title);
          f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
          f.setVisible (true);
        } // main
      
      }// class FileChooseApp
      import javax.swing.*;
      import java.io.*;
      
      /** Filter to work with JFileChooser to select java file types. **/
      public class JavaFilter extends javax.swing.filechooser.FileFilter
      {
        public boolean accept (File f) {
          return f.getName ().toLowerCase ().endsWith (".java")
                || f.isDirectory ();
        }
       
        public String getDescription () {
          return "Java files (*.java)";
        }
      } // class JavaFilter
        

    16. Color Choosers

      //********************************************************************
      //  DisplayColor.java       Author: Lewis/Loftus
      //
      //  Demonstrates the use of a color chooser.
      //********************************************************************
      
      import javax.swing.*;
      import java.awt.*;
      
      public class DisplayColor
      {
         //-----------------------------------------------------------------
         //  Presents a frame with a colored panel, then allows the user
         //  to change the color multiple times using a color chooser.
         //-----------------------------------------------------------------
         public static void main (String[] args)
         {
            JFrame frame = new JFrame ("Display Color");
            frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
      
            JPanel colorPanel = new JPanel();
            colorPanel.setBackground (Color.white);
            colorPanel.setPreferredSize (new Dimension (300, 100));
      
            frame.getContentPane().add (colorPanel);
            frame.pack();
            frame.setVisible(true);
      
            Color shade = Color.white;
            int again;
      
            do 
            {
               shade = JColorChooser.showDialog (frame, "Pick a Color!",
                                                 shade);
      
               colorPanel.setBackground (shade);
      
               again = JOptionPane.showConfirmDialog (null,
                  "Display another color?");
            }
            while (again == JOptionPane.YES_OPTION);
         }
      }
        

    17. Sliders

      //********************************************************************
      //  SlideColor.java       Authors: Lewis/Loftus
      //
      //  Demonstrates the use slider components.
      //********************************************************************
      
      import java.awt.*;
      import javax.swing.*;
      
      public class SlideColor
      {
         //-----------------------------------------------------------------
         //  Presents up a frame with a control panel and a panel that
         //  changes color as the sliders are adjusted.
         //-----------------------------------------------------------------
         public static void main (String[] args)
         {
            JFrame frame = new JFrame ("Slide Colors");
            frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
      
            frame.getContentPane().add(new SlideColorPanel());
      
            frame.pack();
            frame.setVisible(true);
         }
      }
      //********************************************************************
      //  SlideColorPanel.java       Authors: Lewis/Loftus
      //
      //  Represents the slider control panel for the SlideColor program.
      //********************************************************************
      
      import java.awt.*;
      import javax.swing.*;
      import javax.swing.event.*;
      
      public class SlideColorPanel extends JPanel
      {
         private JPanel controls, colorPanel;
         private JSlider rSlider, gSlider, bSlider;
         private JLabel rLabel, gLabel, bLabel;
      
         //-----------------------------------------------------------------
         //  Sets up the sliders and their labels, aligning them along
         //  their left edge using a box layout.
         //-----------------------------------------------------------------
         public SlideColorPanel()
         {
            rSlider = new JSlider (JSlider.HORIZONTAL, 0, 255, 0);
            rSlider.setMajorTickSpacing (50);
            rSlider.setMinorTickSpacing (10);
            rSlider.setPaintTicks (true);
            rSlider.setPaintLabels (true);
            rSlider.setAlignmentX (Component.LEFT_ALIGNMENT);
      
            gSlider = new JSlider (JSlider.HORIZONTAL, 0, 255, 0);
            gSlider.setMajorTickSpacing (50);
            gSlider.setMinorTickSpacing (10);
            gSlider.setPaintTicks (true);
            gSlider.setPaintLabels (true);
            gSlider.setAlignmentX (Component.LEFT_ALIGNMENT);
      
            bSlider = new JSlider (JSlider.HORIZONTAL, 0, 255, 0);
            bSlider.setMajorTickSpacing (50);
            bSlider.setMinorTickSpacing (10);
            bSlider.setPaintTicks (true);
            bSlider.setPaintLabels (true);
            bSlider.setAlignmentX (Component.LEFT_ALIGNMENT);
      
            SliderListener listener = new SliderListener();
            rSlider.addChangeListener (listener);
            gSlider.addChangeListener (listener);
            bSlider.addChangeListener (listener);
      
            rLabel = new JLabel ("Red: 0");
            rLabel.setAlignmentX (Component.LEFT_ALIGNMENT);
            gLabel = new JLabel ("Green: 0");
            gLabel.setAlignmentX (Component.LEFT_ALIGNMENT);
            bLabel = new JLabel ("Blue: 0");
            bLabel.setAlignmentX (Component.LEFT_ALIGNMENT);
      
            controls = new JPanel();
            BoxLayout layout = new BoxLayout (controls, BoxLayout.Y_AXIS);
            controls.setLayout (layout);
            controls.add (rLabel);
            controls.add (rSlider);
            controls.add (Box.createRigidArea (new Dimension (0, 20)));
            controls.add (gLabel);
            controls.add (gSlider);
            controls.add (Box.createRigidArea (new Dimension (0, 20)));
            controls.add (bLabel);
            controls.add (bSlider);
      
            colorPanel = new JPanel();
            colorPanel.setPreferredSize (new Dimension (100, 100));
            colorPanel.setBackground (new Color (0, 0, 0));
            
            add (controls);
            add (colorPanel);
         }
      
         //*****************************************************************
         //  Represents the listener for all three sliders.
         //*****************************************************************
         private class SliderListener implements ChangeListener
         {
            private int red, green, blue;
      
            //--------------------------------------------------------------
            //  Gets the value of each slider, then updates the labels and
            //  the color panel.
            //--------------------------------------------------------------
            public void stateChanged (ChangeEvent event)
            {
               red = rSlider.getValue();
               green = gSlider.getValue();
               blue = bSlider.getValue();
      
               rLabel.setText ("Red: " + red);
               gLabel.setText ("Green: " + green);
               bLabel.setText ("Blue: " + blue);
      
               colorPanel.setBackground (new Color (red, green, blue));
            }
         }
      }
        

    18. Exception Handling

      An exception is an object that defines an unusual or erroneous situation.

      Examples:

    19. attempting to divide by zero
    20. arrary index out of baounds
    21. specified file not found
    22. I/O operation could not be completed normally
    23. security violation
    24. Uncaught exceptions:

      public class Zero
      {
         //-----------------------------------------------------------------
         //  Deliberately divides by zero to produce an exception.
         //-----------------------------------------------------------------
         public static void main (String[] args)
         {
            int numerator = 10;
            int denominator = 0;
       
            System.out.println (numerator / denominator);
       
            System.out.println ("This text will not be printed.");
         }
      }
        
      Output:
      Exception in thread "main" java.lang.ArithmeticException: / by zero at Zero.main(Zero.java:17)

      As exceptions are objects, when you throw an exception, you throw an object. You can't throw just any object as an exception, however -- only those objects whose classes descend from Throwable. Throwable serves as the base class for an entire family of classes, declared in java.lang, that your program can instantiate and throw. A small part of this family is shown in the Figure below.

      An example: Coffee sipping

      The try-catch statement

    25. identifies a block of statements that may throw an exception
    26. a catch clause, following a try block, defines how a particular kind of exception is handled
    27. //********************************************************************
      //  ProductCodes.java       Author: Lewis/Loftus
      //
      //  Demonstrates the use of a try-catch block.
      //********************************************************************
      
      import java.util.Scanner;
      
      public class ProductCodes
      {
         //-----------------------------------------------------------------
         //  Counts the number of product codes that are entered with a
         //  zone of R and and district greater than 2000.
         //-----------------------------------------------------------------
         public static void main (String[] args)
         {
            String code;
            char zone;
            int district, valid = 0, banned = 0;
      
            Scanner scan = new Scanner (System.in);
      
            System.out.print ("Enter product code (XXX to quit): ");
            code = scan.nextLine();
      
            while (!code.equals ("XXX"))
            {
               try
               {
                  zone = code.charAt(9);
                  district = Integer.parseInt(code.substring(3, 7));
                  valid++;
                  if (zone == 'R' && district > 2000)
                     banned++;
               }
               catch (StringIndexOutOfBoundsException exception)
               {
                  System.out.println ("Improper code length: " + code);
               }
               catch (NumberFormatException exception)
               {
                  System.out.println ("District is not numeric: " + code);
               }
      
               System.out.print ("Enter product code (XXX to quit): ");
               code = scan.nextLine();
            }
      
            System.out.println ("# of valid codes entered: " + valid);
            System.out.println ("# of banned codes entered: " + banned);
         }
      }
        

       import java.awt.*;
         import java.awt.event.*;
         import javax.swing.*;
         import java.io.*;
      
         public class ExceptTest
         {
            public static void main(String[] args)
            {
              ExceptTestFrame frame = new ExceptTestFrame();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setVisible(true);
           }
        }
       //    A frame with a panel for testing various exceptions
      
        class ExceptTestFrame extends JFrame
        {
           public ExceptTestFrame()
           {
              setTitle("ExceptTest");
              ExceptTestPanel panel = new ExceptTestPanel();
              getContentPane().add(panel);
              pack();
           }
        }
        /**
           A panel with radio buttons for running code snippets
           and studying their exception behavior
        */
        class ExceptTestPanel extends Box
        {
           public ExceptTestPanel()
           {
              super(BoxLayout.Y_AXIS);
              group = new ButtonGroup();
      
              // add radio buttons for code snippets
      
              addRadioButton("Integer divide by zero", new
                 ActionListener()
                 {
                    public void actionPerformed(ActionEvent event)
                    {
                       a[1] = 1 / (a.length - a.length);
                    }
                 });
       
              addRadioButton("Floating point divide by zero", new
               ActionListener()
               {
                    public void actionPerformed(ActionEvent event)
                    {
                       a[1] = a[2] / (a[3] - a[3]);
                    }
                 });
       
              addRadioButton("Array bounds", new
                 ActionListener()
                 {
                    public void actionPerformed(ActionEvent event)
                    {
                       a[1] = a[10];
                    }
                 });
      
              addRadioButton("Bad cast", new
                 ActionListener()
                 {
                    public void actionPerformed(ActionEvent event)
                    {
                       a = (double[])event.getSource();
                    }
                 });
       
              addRadioButton("Null pointer", new
                 ActionListener()
                 {
                    public void actionPerformed(ActionEvent event)
                    {
                       event = null;
                       System.out.println(event.getSource());
                    }
                 });
      
              addRadioButton("sqrt(-1)", new
                 ActionListener()
                 {
                    public void actionPerformed(ActionEvent event)
                    {
                       a[1] = Math.sqrt(-1);
                    }
                 });
      
              addRadioButton("Overflow", new
                 ActionListener()
                 {
                   public void actionPerformed(ActionEvent event)
                   {
                      a[1] = 1000 * 1000 * 1000 * 1000;
                      int n = (int) a[1];
                   }
                });
      
             addRadioButton("No such file", new
                ActionListener()
                {
                   public void actionPerformed(ActionEvent event)
                   {
                      try
                      {
                         InputStream in = new FileInputStream("woozle.txt");
                      }
                      catch (IOException e)
                      {
                         textField.setText(e.toString());
                      }
                   }
                });
      
             addRadioButton("Throw unknown", new
                ActionListener()
                {
                   public void actionPerformed(ActionEvent event)
                   {
                      throw new UnknownError();
                   }
                });
      
             // add the text field for exception display
             textField = new JTextField(30);
             add(textField);
          }
      
          /**
             Adds a radio button with a given listener to the
             panel. Traps any exceptions in the actionPerformed
             method of the listener.
             @param s the label of the radio button
             @param listener the action listener for the radio button
          */
            private void addRadioButton(String s, ActionListener listener)
          {
             JRadioButton button = new JRadioButton(s, false)
                {
                   // the button calls this method to fire an
                   // action event. We override it to trap exceptions
                   protected void fireActionPerformed(ActionEvent event)
                   {
                      try
                      {
                         textField.setText("No exception");
                         super.fireActionPerformed(event);
                      }
                      catch (Exception e)
                      {
                         textField.setText(e.toString());
                      }
                   }
                };
      
             button.addActionListener(listener);
             add(button);
             group.add(button);
          }
      
          private ButtonGroup group;
          private JTextField textField;
          private double[] a = new double[10];
       }
        

      The finally clause ( optional for try-catch ) defines a seciton of code that is executed no matter how the try block is exited.