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.


13.4 Fill in the blanks in each of the following:

  1. A dedicated drawing area can be defined as a subclass of ________.
  2. A JMenuItem that is a JMenu is called a ________.
  3. Both JTextFields and JTextAreas inherit directly from class ________.
  4. The ________ method attaches a JMenuBar to a JFrame.
  5. Container class ________ has a default BoxLayout.
  6. A ________ manages a set of child windows defined with class JInternalFrame.

13.5 State whether each of the following is true or false. If false, explain why.

  1. Menus require a JMenuBar object so they can be attached to a JFrame.
  2. A JPanel object is capable of receiving mouse events.
  3. CardLayout is the default layout manager for a JFrame.
  4. Method setEditable is a JTextComponent method.
  5. The GridBagLayout layout manager implements LayoutManager.
  6. JPanel objects are containers to which other GUI components can be attached.
  7. Class JFrame inherits directly from class Container.
  8. JApplets can contain menus.

13.6 Find the error(s) in each of the following. Explain how to correct the error(s).

  1. x.add( new JMenuItem( "Submenu Color" ) ); // create submenu
  2. c.setLayout( m = new GridbagLayout() );
  3. String s = JTextArea.getText();

13.7 Write a program that displays a circle of random size and calculates and displays the area, radius, diameter and circumference. Use the following equations: diameter = 2 _ radius, area = p _ radius2, circumference = 2 _ p _ radius. Use the constant Math.PI for pi (p). All drawing should be done on a subclass of JPanel and the results of the calculations should be displayed in a read- only JTextArea.

13.8 Enhance the program of Exercise 13.7 by allowing the user to alter the radius with a JSlider. The program should work for all radii in the range 100 to 200. As the radius changes, the diameter, area and circumference should be updated and displayed. The initial radius should be 150. Use the equations of Exercise

13.7 All drawing should be done on a subclass of JPanel and the results of the calculations should be displayed in a read-only JTextArea.

13.9 Explore the effects of varying the weightx and weighty values of the program of Fig. 13.17. What happens when a component has a nonzero weight, but is not allowed to fill the whole area (i.e., the fill value is not BOTH)?

13.10 Write a program that uses the paint method to draw the current value of a JSlider on a subclass of JPanel. In addition, provide a JTextField where a specific value can be entered. The JTextField should display the current value of the JSlider at all times. A JLabel should be used to identify the JTextField. The JSlider methods setValue and getValue should be used. [Note: The setValue method is a public method that does not return a value and takes one integer argument-the JSlider value, which determines the position of the thumb.]

13.11 Modify the program of Fig. 13.13 to use a single JComboBox instead of the four separate JButtons. Each "card" should not be modified.

13.12 Modify the program of Fig. 13.13 by adding a minimum of two new "cards" to the deck.

13.13 Define a subclass of JPanel called MyColorChooser that provides three JSlider objects and three JTextField objects. Each JSlider represents the values from 0 to 255 for the red, green and blue parts of a color. Use the red, green and blue values as the arguments to the Color constructor to create a new Color object. Display the current value of each JSlider in the corresponding JTextField. When the user changes the value of the JSlider, the JTextField should be changed accordingly. Define class MyColorChooser so it can be reused in other applications or applets. Use your new GUI component as part of an applet that displays the current Color value by drawing a filled rectangle.

13.14 Modify the MyColorChooser class of Exercise 13.13 to allow the user to type an integer value into a JTextField to set the red, green or blue value. When the user presses Enter in the JTextField, the corresponding JSlider should be set to the appropriate value.

13.15 Modify the applet of Exercise 13.14 to draw the current color as a rectangle on an instance of a subclass of JPanel called DrawPanel. Class DrawPanel should provide its own paintComponent method to draw the rectangle and should provide set methods to set the red, green, and blue values for the current color. When any set method is invoked for the class DrawPanel, the object should automatically repaint itself.

13.16 Modify the applet of Exercise 13.15 to allow the user to drag the mouse across the DrawPanel to draw a shape in the current color. Enable the user to choose what shape to draw.

13.17 Modify the program of Exercise 13.16 to enable the program to run as an application. The existing applet's code should only be modified by adding a main method to launch the application in its own JFrame. Provide the user with the ability to terminate the application by clicking the close box on the window that is displayed and by selecting Exit from a File menu. Use the techniques shown in Fig. 13.6.

13.18 (Complete Drawing Application) Using the techniques developed in Exercises 12.27-12.33 and Exercises 13.13-13.17, create a complete drawing program that can execute as both an applet and an application. The program should use the GUI components of Chapters 12 and 13 to enable the user to select the shape, color and fill characteristics. Each shape should be stored in an array of MyShape objects, where MyShape is the superclass in your hierarchy of shape classes (see Exercises 9.28 and 9.29). Use a JDesktopPane and JInternalFrames to allow the user to create multiple separate drawings in separate child windows. Create the user interface as a separate child window containing all the GUI components that allow the user to determine the characteristics of the shape to be drawn. The user can then click in any JInternalFrame to draw the shape.

13.19 A company pays its employees as managers (who receive a fixed weekly salary), hourly workers (who receive a fixed hourly wage for up to the first 40 hours they work and "time-and-a- half," i.e., 1.5 times their hourly wage, for overtime hours worked), commission workers (who receive $250 plus 5.7% of their gross weekly sales) or pieceworkers (who receive a fixed amount of money per item for each of the items they produce-each pieceworker in this company works on only one type of item). Write an application to compute the weekly pay for each employee. Each type of employee has its own pay code: Managers have paycode 1, hourly workers have code 2, commission workers have code 3 and pieceworkers have code 4. Use a switch to compute each employee's pay based on that employee's paycode. Use a CardLayout to display the appropriate GUI components that allow the user to enter the facts your program needs to calculate each employee's pay based on that employee's paycode.


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.


13.4 Fill in the blanks in each of the following:

  1. A dedicated drawing area can be defined as a subclass of .
    ANS: JPanel.
  2. A JMenuItem that is a JMenu is called a .?
    ANS: submenu.
  3. Both JTextFields and JTextAreas inherit directly from class .
    ANS: JTextComponent.
  4. The method attaches a JMenuBar to a JFrame.
    ANS: setJMenuBar.
  5. Container class has a default BoxLayout.
    ANS: Box.
  6. A manages a set of child windows defined with class JInternalFrame.
    ANS: JDesktopPane.

13.5 State whether each of the following is true or false. If false, explain why.

  1. Menus require a JMenuBar object so they can be attached to a JFrame.
    ANS: True.
  2. A JPanel object is capable of receiving mouse events.
    ANS: True.
  3. CardLayout is the default layout manager for a JFrame.
    ANS: True.
  4. Method setEditable is a JTextComponent method.
    ANS: False. BorderLayout is the default layout manager for JFrame.
  5. The GridBagLayout layout manager implements LayoutManager.
    ANS: True.
  6. JPanel objects are containers to which other GUI components can be attached.
    ANS: True.
  7. Class JFrame inherits directly from class Container.
    ANS: False. JFrame inherits directly from Frame.
  8. JApplets can contain menus.
    ANS: True.

13.7

// Exercise 13.7 Solution
// Circle1.java
// Program draws a circle of a random
// diameter and displays the area, diameter,
// and circumference.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Circle1 extends JFrame {
   private CircleCanvas theCanvas;
   private JTextArea display;

   public Circle1()
   {
      super( "Circle1" );
      theCanvas = new CircleCanvas();
      display = new JTextArea( 5, 30 );

      display.setText( "The Radius is: " + theCanvas.getRadius() +
                       "\nThe Diameter is: " + theCanvas.getDiameter()
                       + "\nThe Area is: " + theCanvas.getArea() +
                       "\nThe Circumference is: " +
                       theCanvas.getCircumference() );

      //setLayout( new BorderLayout() );
      getContentPane().add( theCanvas, BorderLayout.CENTER );
      getContentPane().add( display, BorderLayout.SOUTH );
      setSize( 200, 200 );
      show();
   }

   public static void main( String args[] )
   {
      Circle1 app = new Circle1();

      app.addWindowListener(
         new WindowAdapter() {
            public void windowClosing( WindowEvent e )
            {
               System.exit( 0 );
            }
         }
      );
   }
}

class CircleCanvas extends JPanel {
   private int radius;

   public CircleCanvas()
   {
      radius = ( int )( 1 + Math.random() * 100 );
      setSize( 100, 100 );
   }

   public void paintComponent( Graphics g )
   {  g.drawOval( 0, 0, radius, radius );  }

   public int getDiameter()  {  return ( 2 * radius );  }

   public int getCircumference()
   {  return ( int )( 2 * Math.PI * radius );  }

   public int getArea()
   {  return ( int )( radius * radius * Math.PI );  }

   public int getRadius()  {  return radius;  }
}

13.10

// Exercise 13.10 Solution
// DrawValue.java
// Program draws the value of
// the scrollbar on a canvas,
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;

public class DrawValue extends JFrame {
   private DrawCanvas canvas;
   private JTextField display;
   private JLabel label;
   private JSlider slider;
   private JPanel p;

   public DrawValue()
   {      
      super( "DrawValue" );
      label = new JLabel( "Value:" );

      p = new JPanel();
      p.setLayout( new GridLayout( 1, 3 ) );

      canvas = new DrawCanvas();
      slider = new JSlider( SwingConstants.HORIZONTAL,
                              0, 200, 10 );
      slider.addChangeListener( 
        new ChangeListener() {
           public void stateChanged( ChangeEvent e )
           {
              canvas.setNumber( slider.getValue() );
              display.setText( String.valueOf( slider.getValue() ) );
           }
        }
      );
      display = new JTextField( "0", 5 );
      display.addActionListener(
         new ActionListener() {
            public void actionPerformed( ActionEvent e )
            {
               int v = Integer.parseInt( display.getText() );

               if ( v < slider.getMinimum() || v > slider.getMaximum() )
                  return;

               canvas.setNumber( v );
               slider.setValue( v );
            }
         }
      );
      p.add( label );
      p.add( display );
      p.add( slider );

      getContentPane().add( canvas, BorderLayout.CENTER );
      getContentPane().add( p, BorderLayout.NORTH );
      setSize( 300, 300 );
      show();
   }

   public static void main( String args[] )
   {
      DrawValue app = new DrawValue(); 

      app.addWindowListener(
         new WindowAdapter() {
            public void windowClosing( WindowEvent e )
            {
               System.exit( 0 );
            }
         }
      );
   }
}

class DrawCanvas extends JPanel {
   private int number;
   private Font f;

   public DrawCanvas()
   {
      setBackground( Color.black );
      setSize( 200, 200 );
      f = new Font( "Serif", Font.BOLD, 99 );
   }

   public void setNumber( int n )
   {
      number = n;
      repaint();
   }

   public void paintComponent( Graphics g )
   {
      super.paintComponent( g );
      g.setFont( f );
      g.setColor( Color.red );
      g.drawString( String.valueOf( number ),
                    getSize().width / 2 - 40,
                    getSize().height / 2 );
   }

   public int getNumber()  { return number; }
}

13.11

// Example 13.11: CardDeck.java
// Demonstrating CardLayout.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;

public class CardDeck extends JFrame {
   private CardLayout cardManager;
   private JPanel deck;
   private JList control;   
   private String names[] = { "First card", "Next card",
                              "Previous card", "Last card" };

   public CardDeck()
   {
      super( "CardLayout " );

      Container c = getContentPane();

      // create the JPanel with CardLayout
      deck = new JPanel();
      cardManager = new CardLayout(); 
      deck.setLayout( cardManager );  

      // set up card1 and add it to JPanel deck
      JLabel label1 =
         new JLabel( "card one", SwingConstants.CENTER );
      JPanel card1 = new JPanel();
      card1.add( label1 ); 
      deck.add( card1, label1.getText() ); // add card to deck
      
      // set up card2 and add it to JPanel deck
      JLabel label2 =
         new JLabel( "card two", SwingConstants.CENTER );
      JPanel card2 = new JPanel();
      card2.setBackground( Color.yellow );
      card2.add( label2 );
      deck.add( card2, label2.getText() ); // add card to deck

      // set up card3 and add it to JPanel deck
      JLabel label3 = new JLabel( "card three" );
      JPanel card3 = new JPanel();
      card3.setLayout( new BorderLayout() );  
      card3.add( new JButton( "North" ), BorderLayout.NORTH );
      card3.add( new JButton( "West" ), BorderLayout.WEST );
      card3.add( new JButton( "East" ), BorderLayout.EAST );
      card3.add( new JButton( "South" ), BorderLayout.SOUTH );
      card3.add( label3, BorderLayout.CENTER );
      deck.add( card3, label3.getText() ); // add card to deck

      // create and layout buttons that will control deck
      control = new JList( names );
      control.addListSelectionListener( 
         new ListSelectionListener() {
            public void valueChanged( ListSelectionEvent e )
            {         
              switch( control.getSelectedIndex() ) {
                 case 0:
                    cardManager.first( deck ); // show first card
                    break;
                 case 1:
                    cardManager.next( deck );  // show next card                   
                    break;  
                 case 2:
                    cardManager.previous( deck );  // show previous card                   
                    break;
                 case 3:
                    cardManager.last( deck );  // show last card            
                    break;
              }
            }
         }
      );

      c.add( control, BorderLayout.CENTER );
      c.add( deck, BorderLayout.EAST );

      setSize( 450, 200 );
      show();
   }

   public static void main( String args[] )
   {
      CardDeck cardDeckDemo = new CardDeck();

      cardDeckDemo.addWindowListener(
         new WindowAdapter() {
            public void windowClosing( WindowEvent e )
            {
               System.exit( 0 );
            }
         }
      );
   }
}

13.13

// Exercise 13.13 Solution
// Palette.java
// Program allows the user to create
// a custom color.
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;

public class Palette extends JApplet
            implements ChangeListener {
   private MyColorChooser colorChooser;

   public void init()
   {
      colorChooser = new MyColorChooser( this );
      getContentPane().add( colorChooser, BorderLayout.SOUTH );
   }

   public void paint( Graphics g )
   {
      g.setColor( colorChooser.getColor() );
      g.fillRect( 50, 50, 50, 50 );
   }

   public void stateChanged( ChangeEvent e )
   {
      repaint();
   }
}

class MyColorChooser extends JPanel
{
   private JSlider redSlider, blueSlider, greenSlider;
   private JTextField redDisplay, blueDisplay, greenDisplay;
   private JLabel redLabel, blueLabel, greenLabel;
   private Color color;

   public MyColorChooser( ChangeListener parent )
   {
      redSlider = new JSlider( SwingConstants.HORIZONTAL, 0, 255, 1 );
      blueSlider = new JSlider( SwingConstants.HORIZONTAL, 0, 255, 1 );
      greenSlider = new JSlider( SwingConstants.HORIZONTAL, 0, 255, 1 );

      redDisplay = new JTextField( "0", 4 );
      blueDisplay = new JTextField( "0", 4 );
      greenDisplay = new JTextField( "0", 4 );
      redDisplay.setEditable( false );
      blueDisplay.setEditable( false );
      greenDisplay.setEditable( false );

      redLabel = new JLabel( "Red:" );
      blueLabel = new JLabel( "Blue:" );
      greenLabel = new JLabel( "Green:" );

      setLayout( new GridLayout( 3, 3 ) );

      add( redLabel );
      add( redSlider );
      add( redDisplay );
      add( greenLabel );
      add( greenSlider );
      add( greenDisplay );
      add( blueLabel );
      add( blueSlider );
      add( blueDisplay );

      redSlider.addChangeListener( new ChangeHandler() );
      greenSlider.addChangeListener( new ChangeHandler() );
      blueSlider.addChangeListener( new ChangeHandler() );
      redSlider.addChangeListener( parent );
      greenSlider.addChangeListener( parent );
      blueSlider.addChangeListener( parent );
 
      color = Color.black;
   }

   public void setColor( Color c ) { color = c; }
   public Color getColor() { return ( color ); }

   private class ChangeHandler implements ChangeListener {
      public void stateChanged( ChangeEvent e )
      {
         int r = redSlider.getValue();
         int b = blueSlider.getValue();
         int g = greenSlider.getValue();

         redDisplay.setText( String.valueOf( r ) );
         blueDisplay.setText( String.valueOf( b ) );
         greenDisplay.setText( String.valueOf( g ) );

         setColor( new Color( r, g, b ) );
         repaint();
      }
   }
}