Answers to Self Review Exercises


a) mouseMoved. b) uneditable (read-only). c) layout manager. d) Container. e) graphical user interface. f) setLayout. g) mousePressed, mouseReleased. h) JOptionPane. i) showInputDialog, JOptionPane. j) showMessageDialog, JOptionPane. k) JTextComponent.

  1. True.
  2. False. Method mouseEntered is called.
  3. False. A JPanel can be added to another JPanel, because JPanel is an indirect subclass of Component. Therefore, a JPanel is a Component. Any Component can be added to a Container.
  4. False. Only the last button added will be displayed. Remember that only one component should be added to each region in a BorderLayout.
  5. True.
  6. False. Inner classes have access to all members of the enclosing class declaration.
  7. False. JTextAreas are editable by default.
  8. False. JTextArea derives from class JTextComponent.
  1. new is needed to create an object.
  2. JLabel is a class name and cannot be used as a variable name.
  3. The arguments passed to the constructor are reversed. The String must be passed first.
  4. BorderLayout has been set, and components are being added without specifying the region so both are added to the center region. Proper add statements might be

    container.add( button1, BorderLayout.NORTH );
    container.add( button2, BorderLayout.SOUTH );



Fill in the blanks in each of the following statements:

  1. The JTextField class directly extends class __________.
  2. Container method __________ attaches a GUI component to a container.
  3. Method __________ is called when a mouse button is released (without moving the mouse).
  4. The __________ class is used to create a group of JRadioButtons.

Determine whether each statement is true or false. If false, explain why.

  1. Only one layout manager can be used per Container.
  2. GUI components can be added to a Container in any order in a BorderLayout.
  3. JRadioButtons provide a series of mutually exclusive options (i.e., only one can be true at a time).
  4. Graphics method setFont is used to set the font for text fields.
  5. A JList displays a scrollbar if there are more items in the list than can be displayed.
  6. A Mouse object has a method called mouseDragged.

Determine whether each statement is true or false. If false, explain why.

  1. A JPanel is a JComponent.
  2. A JPanel is a Component.
  3. A JLabel is a Container.
  4. A JList is a JPanel.
  5. An AbstractButton is a JButton.
  6. A JTextField is an Object.
  7. ButtonGroup is a subclass of JComponent.

Find any errors in each of the following lines of code, and explain how to correct them.

  1. import javax.swing.JFrame
  2. panelObject.GridLayout( 8, 8 ); // set GridLayout
  3. container.setLayout( new FlowLayout( FlowLayout.DEFAULT ) );
  4. container.add( eastButton, EAST ); // BorderLayout

Create the following GUI. You do not have to provide any functionality.


Create the following GUI. You do not have to provide any functionality.


Create the following GUI. You do not have to provide any functionality.


Create the following GUI. You do not have to provide any functionality.


Write a temperature conversion application that converts from Fahrenheit to Celsius. The Fahrenheit temperature should be entered from the keyboard (via a JTextField). A JLabel should be used to display the converted temperature. Use the following formula for the conversion:


Enhance the temperature conversion application of Exercise 11.12 by adding the Kelvin temperature scale. The application should also allow the user to make conversions between any two scales. Use the following formula for the conversion between Kelvin and Celsius (in addition to the formula in Exercise 11.12):


Write an application that displays events as they occur in a JTextArea. Provide a JComboBox with a minimum of four items. The user should be able to choose an event to monitor from the JComboBox. When that particular event occurs, display information about the event in the JTextArea. Use method to String on the event object to convert it to a string representation.


Write an application that plays "guess the number" as follows: Your application chooses the number to be guessed by selecting an integer at random in the range 11000. The application then displays the following in a label:

 I have a number between 1 and 1000. Can you guess my number?
 Please enter your first guess.

A JTextField should be used to input the guess. As each guess is input, the background color should change to either red or blue. Red indicates that the user is getting "warmer," and blue indicates that the user is getting "colder." A JLabel should display either "Too High" or "Too Low" to help the user zero in on the correct answer. When the user gets the correct answer, "Correct!" should be displayed, and the JTextField used for input should be changed to be uneditable. A JButton should be provided to allow the user to play the game again. When the JButton is clicked, a new random number should be generated and the input JTextField changed to be editable.


It is often useful to display the events that occur during the execution of an application. This can help you understand when the events occur and how they are generated. Write an application that enables the user to generate and process every event discussed in this chapter. The application should provide methods from the ActionListener, ItemListener, ListSelectionListener, MouseListener, MouseMotionListener and KeyListener interfaces to display messages when the events occur. Use method toString to convert the event objects received in each event handler into a String that can be displayed. Method toString creates a String containing all the information in the event object.


Modify the application of Section 6.10 to provide a GUI that enables the user to click a JButton to roll the dice. The application should also display four JLabels and four JTextFields, with one JLabel for each JTextField. The JTextFields should be used to display the values of each die and the sum of the dice after each roll. The point should be displayed in the fourth JTextField when the user does not win or lose on the first roll and should continue to be displayed until the game is lost.

(Optional) GUI and Graphics Case Study Exercise: Expanding the Interface


In this exercise, you will implement a GUI application that uses the MyShape hierarchy from Exercise 10.10 to create an interactive drawing application. You will create two classes for the GUI and provide a test class that launches the application. The classes of the MyShape hierarchy require no additional changes.

The first class to create is a subclass of JPanel called DrawPanel, which represents the area on which the user draws the shapes. Class DrawPanel should have the following instance variables:

  1. An array shapes of type MyShape that will store all the shapes the user draws.
  2. An integer shapeCount that counts the number of shapes in the array.
  3. An integer shapeType that determines the type of shape to draw.
  4. A MyShape currentShape that represents the current shape the user is drawing.
  5. A Color currentColor that represents the current drawing color.
  6. A boolean filledShape that determines whether to draw a filled shape.
  7. A JLabel statusLabel that represents the status bar. The status bar will display the coordinates of the current mouse position.

Class DrawPanel should also declare the following methods:

  1. Overridden method paintComponent that draws the shapes in the array. Use instance variable shapeCount to determine how many shapes to draw. Method paintComponent should also call currentShape's draw method, provided that currentShape is not null.
  2. Set methods for the shapeType, currentColor and filledShape.
  3. Method clearLastShape should clear the last shape drawn by decrementing instance variable shapeCount. Ensure that shapeCount is never less than zero.
  4. Method clearDrawing should remove all the shapes in the current drawing by setting shapeCount to zero.

Methods clearLastShape and clearDrawing should call method repaint (inherited from JPanel) to refresh the drawing on the DrawPanel by indicating that the system should call method paintComponent.

Class DrawPanel should also provide event handling to enable the user to draw with the mouse. Create a single inner class that both extends MouseAdapter and implements MouseMotionListener to handle all mouse events in one class.

In the inner class, override method mousePressed so that it assigns currentShape a new shape of the type specified by shapeType and initializes both points to the mouse position. Next, override method mouseReleased to finish drawing the current shape and place it in the array. Set the second point of currentShape to the current mouse position and add currentShape to the array. Instance variable shapeCount determines the insertion index. Set currentShape to null and call method repaint to update the drawing with the new shape.

Override method mouseMoved to set the text of the statusLabel so that it displays the mouse coordinatesthis will update the label with the coordinates every time the user moves (but does not drag) the mouse within the DrawPanel. Next, override method mouseDragged so that it sets the second point of the currentShape to the current mouse position and calls method repaint. This will allow the user to see the shape while dragging the mouse. Also, update the JLabel in mouseDragged with the current position of the mouse.

Create a constructor for DrawPanel that has a single JLabel parameter. In the constructor, initialize statusLabel with the value passed to the parameter. Also initialize array shapes with 100 entries, shapeCount to 0, shapeType to the value that represents a line, currentShape to null and currentColor to Color.BLACK. The constructor should then set the background color of the DrawPanel to Color.WHITE and register the MouseListener and MouseMotionLister so the JPanel properly handles mouse events.

Next, create a JFrame subclass called DrawFrame that provides a GUI that enables the user to control various aspects of drawing. For the layout of the DrawFrame, we recommend a BorderLayout, with the components in the NORTH region, the main drawing panel in the CENTER region, and a status bar in the SOUTH region, as in Fig. 11.49. In the top panel, create the components listed below. Each component's event handler should call the appropriate method in class DrawPanel.

Figure 11.49. Interface for drawing shapes.

(This item is displayed on page 594 in the print version)

  1. A button to undo the last shape drawn.
  2. A button to clear all shapes from the drawing.
  3. A combo box for selecting the color from the 13 predefined colors.
  4. A combo box for selecting the shape to draw.
  5. A check box that specifies whether a shape should be filled or unfilled.

Declare and create the interface components in DrawFrame's constructor. You will need to create the status bar JLabel before you create the DrawPanel, so you can pass the JLabel as an argument to DrawPanel's constructor. Finally, create a test class that initializes and displays the DrawFrame to execute the application.

Introduction to Computers, the Internet and the World Wide Web

Introduction to Java Applications

Introduction to Classes and Objects

Control Statements: Part I

Control Statements: Part 2

Methods: A Deeper Look


Classes and Objects: A Deeper Look

Object-Oriented Programming: Inheritance

Object-Oriented Programming: Polymorphism

GUI Components: Part 1

Graphics and Java 2D™

Exception Handling

Files and Streams


Searching and Sorting

Data Structures



Introduction to Java Applets

Multimedia: Applets and Applications

GUI Components: Part 2



Accessing Databases with JDBC


JavaServer Pages (JSP)

Formatted Output

Strings, Characters and Regular Expressions

Appendix A. Operator Precedence Chart

Appendix B. ASCII Character Set

Appendix C. Keywords and Reserved Words

Appendix D. Primitive Types

Appendix E. (On CD) Number Systems

Appendix F. (On CD) Unicode®

Appendix G. Using the Java API Documentation

Appendix H. (On CD) Creating Documentation with javadoc

Appendix I. (On CD) Bit Manipulation

Appendix J. (On CD) ATM Case Study Code

Appendix K. (On CD) Labeled break and continue Statements

Appendix L. (On CD) UML 2: Additional Diagram Types

Appendix M. (On CD) Design Patterns

Appendix N. Using the Debugger

Inside Back Cover

show all menu

Java(c) How to Program
Java How to Program (6th Edition) (How to Program (Deitel))
ISBN: 0131483986
EAN: 2147483647
Year: 2003
Pages: 615
Similar book on Amazon

Flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net