Exercises

Included below are short-answer and programming exercises. Answers are provided for those exercises whose exercise number is a hyperlink. Because college faculty use these exercises in their exams, we have provided answers to roughly half of the exercises included here.


25.2 Try each of the demonstration JavaBeans supplied with the BeanBox. The documentation that comes with the BDK provides overviews of the demonstration beans. While using each bean, try the following:

  1. Inspect the properties of each bean and try modifying them.
  2. Inspect the events supported by each bean and try using those events to hook various demonstration beans together.

25.3 Using the SliderFieldPanel as a foundation, create your own ColorSelector GUI component that contains three instances of our SliderFieldPanel bean. Each should have values in the range 0 to 255 for the red, green and blue parts of a color. The programmer using your bean should be able configure the default color when their application executes. Make color a bound property such that other objects can be notified when the color changes. Test your bean in the BeanBox by changing the background color of the BeanBox when a new color is selected. To specify the BeanBox as the target of an event, simply aim the target selector line at the background of the BeanBox window and click.

25.4 Modify Exercise 25.3 to provide a mechanism for viewing the selected color. For this purpose add a JPanel object to the bean. Test your bean in the BeanBox by changing the background color of the BeanBox when a new color is selected.

25.5 Create a BeanInfo class for the LogoAnimator2 bean that exposes only the background and animationDelay properties. Test your bean in the BeanBox.

25.6 Using the graphics techniques discussed in Chapter 11, implement your own subclass of JPanel that supports drawing of a variety of shapes. The user should be able to select which shape to draw, then use the mouse to draw the shape. All shapes should be maintained as objects in a hierarchy of shape types. You can use either of the hierarchies described in Exercises 9.28 and 9.29, or you can use the predefined classes of the Java2D API as discussed in Chapter 11. Store all the shape objects in a Vector. Wrap your class as a JavaBean and test it in the BeanBox.

25.7 Modify your solution to Exercise 25.6 to allow the user to select the color and fill characteristics of the shape. Wrap your class as a JavaBean and test it in the BeanBox.

25.8 Add a saveShapes method and a loadShapes method to the JavaBean in Exercise 25.7. Method saveShapes should store a Vector of objects to a file on disk, and method loadShapes should load a Vector of objects from a file on disk. Both methods should take no arguments–the Vector should be part of the bean. The file should be manipulated with the object serialization techniques discussed in Chapter 17. When method saveShapes is called, display a JFileChooser dialog that allows the user to select a file in which to save the Vector’s contents, then write the Vector into the file. When method loadShapes is called, display a JFileChooser dialog that allows the user to select a file from which to read the Vector’s contents, then load the Vector. Wrap your class as a JavaBean and test it in the BeanBox. Hook up a button to your bean such that when the button is pressed, method saveShapes is called. Hook up a second button to your bean such that when the button is pressed, method loadShapes is called.


Selected Answers

Included below are answers to approximately half the of the exercises in the Cyber Classroom. We are not able to include answers to every exercise because college faculty use these exercises in their classroom exams.


25.5

// Exercise 25.5 Solution// Animation bean with animationDelay propertypackage jhtp3beans;import java.awt.*;import java.awt.event.*;import javax.swing.*;public class LogoAnimator2 extends LogoAnimator {   // the following two methods are   // for the animationDelay property   public void setAnimationDelay( int value )   {      animationDelay = value;      animationTimer.setDelay( animationDelay );   }   public int getAnimationDelay()   {      return animationTimer.getDelay();   }   public static void main( String args[] )   {      LogoAnimator2 anim = new LogoAnimator2();      JFrame app = new JFrame( "Animator test" );      app.getContentPane().add( anim, BorderLayout.CENTER );      app.addWindowListener(         new WindowAdapter() {            public void windowClosing( WindowEvent e )            {               System.exit( 0 );            }         }      );      app.setSize( anim.getPreferredSize().width + 10,                 anim.getPreferredSize().height + 30 );      app.show();   }}/************************************************************************** * (C) Copyright 1999 by Deitel & Associates, Inc. and Prentice Hall.     * * All Rights Reserved.                                                   * *                                                                        * * DISCLAIMER: The authors and publisher of this book have used their     * * best efforts in preparing the book. These efforts include the          * * development, research, and testing of the theories and programs        * * to determine their effectiveness. The authors and publisher make       * * no warranty of any kind, expressed or implied, with regard to these    * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or       * * consequential damages in connection with, or arising out of, the       * * furnishing, performance, or use of these programs.                     * *************************************************************************/// Animation beanpackage jhtp3beans;import java.awt.*;import java.awt.event.*;import java.io.*;import java.net.*;import javax.swing.*;public class LogoAnimator extends JPanel       implements ActionListener, Serializable {   protected ImageIcon images[];   protected int totalImages = 30,                 currentImage = 0,                 animationDelay = 50; // 50 millisecond delay   protected Timer animationTimer;   public LogoAnimator()   {      setSize( getPreferredSize() );      images = new ImageIcon[ totalImages ];      URL url;      for ( int i = 0; i < images.length; ++i ) {         url = getClass().getResource(                  "deitel" + i + ".gif" );         images[ i ] = new ImageIcon( url );      }      startAnimation();   }   public void paintComponent( Graphics g )   {      super.paintComponent( g );      if ( images[ currentImage ].getImageLoadStatus() ==           MediaTracker.COMPLETE ) {         g.setColor( getBackground() );         g.drawRect(            0, 0, getSize().width, getSize().height );         images[ currentImage ].paintIcon( this, g, 0, 0 );         currentImage = ( currentImage + 1 ) % totalImages;      }   }   public void actionPerformed( ActionEvent e )   {      repaint();   }   public void startAnimation()   {      if ( animationTimer == null ) {         currentImage = 0;           animationTimer = new Timer( animationDelay, this );         animationTimer.start();      }      else  // continue from last image displayed         if ( ! animationTimer.isRunning() )            animationTimer.restart();   }   public void stopAnimation()   {      animationTimer.stop();   }   public Dimension getMinimumSize()   {       return getPreferredSize();    }   public Dimension getPreferredSize()   {      return new Dimension( 160, 80 );   }   public static void main( String args[] )   {      LogoAnimator anim = new LogoAnimator();      JFrame app = new JFrame( "Animator test" );      app.getContentPane().add( anim, BorderLayout.CENTER );      app.addWindowListener(         new WindowAdapter() {            public void windowClosing( WindowEvent e )            {               System.exit( 0 );            }         }      );      app.setSize( anim.getPreferredSize().width + 10,                   anim.getPreferredSize().height + 30 );      app.show();   }}/************************************************************************** * (C) Copyright 1999 by Deitel & Associates, Inc. and Prentice Hall.     * * All Rights Reserved.                                                   * *                                                                        * * DISCLAIMER: The authors and publisher of this book have used their     * * best efforts in preparing the book. These efforts include the          * * development, research, and testing of the theories and programs        * * to determine their effectiveness. The authors and publisher make       * * no warranty of any kind, expressed or implied, with regard to these    * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or       * * consequential damages in connection with, or arising out of, the       * * furnishing, performance, or use of these programs.                     * *************************************************************************/// LogoAnimator2BeanInfo.javapackage jhtp3beans;import java.beans.*;public class LogoAnimator2BeanInfo extends SimpleBeanInfo {   private final static Class beanClass = LogoAnimator2.class;   public PropertyDescriptor[] getPropertyDescriptors()   {      try {         PropertyDescriptor background =            new PropertyDescriptor( "background", beanClass );         PropertyDescriptor animationDelay =            new PropertyDescriptor( "animationDelay", beanClass );         PropertyDescriptor desciptors[] = { background, animationDelay };         return desciptors;      }      catch ( IntrospectionException ie ) {         throw new RuntimeException( ie.toString() );      }   }   public int getDefaultPropertyIndex()   {      return 1;   }}