OKCancel dialog?" and "Why doesn't Java have a standard MessageBox?" In this Java tip, I've provided one solution that takes into
account all of these questions. So what's this all-encompassing answer? A reusable MessageBox class (for Java 1.1 or later versions) that allows you to display a message and clickable buttons in a browser window and
gather a response from the user. It comes in the form of a JavaBean.Let's consider what we want from a use case point of view. A use case is a series of steps an actor performs to accomplish a goal. Putting our analyst hats on, it would be nice if we had a MessageBox class that allowed us to ask a user a question and get a response, say, as follows:
MessageBox box = new MessageBox(this);
box.setTitle("Delete Confirmation");
box.addChoice("Yes", "DeleteConfirmYes");
box.addChoice("No", "DeleteConfirmNo");
box.addChoice("Help", "DeleteConfirmHelp");
box.setCloseWindowCommand("DeleteConfirmNo");
box.ask("Do you really want to delete this customer?");
The above code is a use case at the lowest possible level. Note that we can configure the MessageBox for a wide variety of uses -- not just a limited one that provides the responses "Yes," "No," or "Cancel." It's a common
beginner's error to build a MessageBox that handles only a few combinations of buttons. But once you begin to understand configurability, as is demonstrated in
this simple MessageBox, you are on the path to designing reusable classes.
To receive notification that a button was clicked, we must implement ActionListener and test for the action command in public void actionPerformed(Action evt).
For MessageBox to be a top-notch reusable class, we need a few more features. For example, what if we have a Frame and are opening a modal dialog box by using MessageBox? Shouldn't we provide MessageBox with our Frame so that when the MessageBox is gone, the focus will return to the Frame? What we need to add is the following optional use case feature:
box.setFrame(myFrame);
With GUIs getting more polished all the time on the Web, how can we snazz up our MessageBox and provide the user with a more conceptual ease of use? One way to achieve this is by allowing an image to be displayed
along with the message. For this, we need to add an additional optional use case feature:
box.useImageCanvas(lightBulbImage);
But this means the client must create the image, and often the client simply wants to use a standard image in the same directory
as MessageBox. In this case, we would like an easier method:
box.useImageCanvas("LightBulb.gif");
What if we find ourselves frequently using MessageBox to as questions that demand yes and no answers, thus creating "Yes" and "No" answer boxes? What if, even more often, we ask
questions that are best answered with "Okay"? In that case, the more useful features would be:
cvzxvzBy Anonymous on September 9, 2009, 12:58 pmvzxcvczx
Reply | Read entire comment
View all comments