Personal tools
You are here: Home Information Systems Java Platform Introduction Exercises Exercises 7

Exercises 7

Document Actions
  • Send this
  • Print this
  • Content View
  • Bookmarks

Exercises 7

<-- Previous

Table of Contents

Next -->

EXERCISE A.

You have all seen and used dialog (message) boxes before, when writing scripts in Javascript or VBScript - see below:

Java has a similar on-screen dialog box that can be created by using the javax.swing.JOptionPane class. This is not quite as simple as using JOptionPane.showInputDialog() however. To be able to use simple message dialogs, we must understand a little more about using the javax.swing classes.

All graphic user interfaces (GUI's) produced with the Swing classes, need to be built inside containers that hold all the objects in the GUI. Specifically, every Swing GUI must have a top-level container. A top-level Swing container provides the support that Swing components need to perform their painting and event handling. Examples of top-level container classes are:

  • Applet
  • Dialog
  • Frame

Every dialog is dependent on a frame. When that frame is destroyed, so are its dependent dialogs. A JFrame is an object that holds other swing components, such as a dialog box. To set up a swing GUI, we must:

  1. Import the packages/classes we need.
  2. Set up a top-level container such as a Frame.

To produce a message dialog, we use the
JOptionPane.showMessageDialog(Component parentComponent, Object message)
method. Consider the code shown below; it produces a simple dialog:

Download, compile and run DemoDialog.java - this is what you should see (or something very similar):

Note that the top-level container frame and a String object are the arguments for the showMessageDialog() method.

Adjust the constructor of the NewGreeter class so that if a null string is entered into the input dialog as the person's name, a dialog will be displayed showing the message: Please enter a name! When the user clicks the OK button on the message dialog, the input dialog must be shown again to accept the name of the person to be greeted. This process should repeat until a string is entered in the input dialog. Below is an illustration of the flow of events (from left to right and downwards):

Hint - A Java while{} construct is built as follows:

while(expression){
    statement(s)
}

EXERCISE B.

In the NewGreeter class, if the user clicks the 'Cancel' button on the input dialog, a NullPointerException is thrown by the constructor. This happens because by simply cancelling the input dialog, we leave nothing (not even a null string) for the constructor to assign to the instance variable name in the
name = JOptionPane.showInputDialog("Enter the name of a person:");
instruction. showInputDialog() is supposed to return an object (String object), but in this case no object has been instantiated in memory for the pointer to point to, and a NullPointerException is thrown.

Write an error-handler in the constructor to deal with this problem, which returns code execution safely to the console, and sends the user a sensible message.

EXERCISE C

JOptionPane.showMessageDialog() has other overloaded methods. The

JOptionPane.showMessageDialog(Component parentComponent, 
		Object message,
		String title, 
		int messageType)
method when used with the following arguments
JOptionPane.showMessageDialog(frame,
		"This is a warning message!", 
		"Warning!", 
		JOptionPane.WARNING_MESSAGE)
(assuming that JFrame frame has been declared earlier) produces a dialog as in the image below:

Note that the parameter int messageType assigns an icon to the dialog box - a warning icon in this case. Use the Javadocs to explore javax.swing.JOptionPane to see the details of using message dialogs.

Note also that JOptionPane.WARNING_MESSAGE is a public class variable of JOptionPane; specifically it is an integer constant. Public class and instance variables are very often constant values that need to be accessed publicly from the class or an instance of the class. For example, in our original 6-sided Die class, we could have declared

public static final int SIDES = 6;
so that Die.SIDES could have been called to return the number of sides of the die. public allows access to the value directly without going through any method; static declares it a class variable so that it can be accessed without needing to instantiate a Die object. In addition, we might have declared
public static int throwMe(){
   return (int)Math.random() * SIDES + 1;
}

so that there was no need to ever instantiate a Die in order to be able to access its number of sides, or throw it. Use the following link to access the javadocs to just such a Die class, and download this particular Die.java and TestDie.java if you like.

Finally, using the Java documentation to assist you, adjust the constructor of the NewGreeter class so that the exception handler produces a message dialog that sends the user a message as follows in the image below, instead of writing to the console:

Thereafter, the exception handler must return execution safely to the console.

EXERCISE D

In Java we can deliberately throw an exception by using the throw keyword:

throw new IllegalArgumentException();
We can do this because exceptions are classes just like any other and can be instantiated. If we wish to deliberately throw an exception, we usually need to import the exception class we need into the class in which it will be thrown. If we handle the thrown exception within the class there is no need to specify that the class throws the specific exception.
import java.lang.IllegalArgumentException;
/**
* Demonstrates deliberately throwing and handling an exception.
*/
public class TestThrowException {
   public static void main(String[] args){
      try {
         throw new IllegalArgumentException();
      } catch(IllegalArgumentException e){
         System.out.println("\nIllegalArgumentException caught!");
      }
   }
}

Adjust class Die so that it will no longer allow a number of throws less than 1, nor a number of sides less than 2. Use the Java IllegalArgumentException class to trap both of these errors, terminating code execution if a number of throws less than 1 is attempted in the throwMe(int times) method, or a number of sides less than 2 is detected in the Die(int numSides) constructor.

EXERCISE E

Adjust class BankAccount to throw a sensible exception class if a withdrawal amount exceeds the account balance.

Final Note: The JOptionPane dialogs we have placed into the NewGreeter class in this exercise are only sensible because we know that Greeter is being used to demonstrate using the javax.swing classes. Generally exception handling should not make use of the swing classes if the class being designed is intended for general use. If GUI objects are required, the programmer making use of your classes should implement these to handle the output of your class. If you don't know what context your classes will be used in, it's better to make the responses generic so that the classes using your class can tailor their implementation accordingly. If your classes are designed to be specifically used in a GUI environment, e.g. as helper classes for a GUI-driven application, that's a different story.

<-- Previous

Table of Contents

Next -->

© G. Hearn, & University of the Western Cape, 2006

 

Copyright 2007-2008, by the Contributing Authors. Cite/attribute Resource. Exercises 7. (2008, July 16). Retrieved June 19, 2013, from UWC Free Courseware Web site: http://free.uwc.ac.za/freecourseware/information-systems/java-platform-introduction/exercises/exercises-7. This work is licensed under a Creative Commons License : Attribution-ShareAlike 3.0. Creative Commons License : Attribution-ShareAlike 3.0