Test Your Thinking
The graphical interface to your program can be a very important part of the overall program. If a program is hard to use, people won’t want to use it. Always remember that the U is GUI stands for User. You don’t yet have all of the tools needed to make a complete GUI (those chapters are coming up), but understanding the basic building blocks of a GUI is a key part of building the entire user interface.
1. Write code to create Figure 6.1, the sample GUI components.
Answer: Naturally, your code will not be identical to that which we have provided. So long as your application creates a window that looks like Figure 6.1, you have completed this section successfully. If your window looks markedly different, use our code example to determine where you can make appropriate modifications.
The most important lessons to be learned from this exercise are determination of which classes represent common GUI components, and how these classes are used to create a simple GUI. If you encountered difficulties with determining which class represents a given component, skim the chapter once again. If you encountered difficulties with the use of a component, you can either take a look back at the chapter or use the Java API Documentation to answer any questions you may have. The API Documentation is a very powerful and easy to use tool—become familiar with it and your skill set will increase dramatically.
Within our example, we added a few optional features for demonstration purposes. First, we added both radio buttons to a ButtonGroup object so that they would act as radio buttons should. As you may recall from the chapter, if you do not add radio buttons to a ButtonGroup the buttons will not be mutually-exclusive.
Second, we added code to shutdown the application when the window is closed. This code should look familiar, as it has been included within several of the examples within the chapter. Don’t worry about the details of this code just yet; this introduces event handling, which is covered in a later chapter.
Lastly, we explicitly sized the application window. Sure, you could simply have stretched the window to the appropriate size; we simply took the liberty of setting the initial size before displaying the window.
Another point worth mentioning is that we set the layout manager of the content pane to FlowLayout. Layout management is discussed in a following chapter, so suffice it to say that this layout type arranges items arbitrarily according to the current window size. Other layout managers are able to perform more explicit layout operations, but for our needs this was the simplest choice.
So, how does your application look? In what ways did your code differ from our example? Take a moment to compare and contrast your code with ours. By casting a critical eye on both examples, you will begin to formulate your own programming style.
Click here to view SampleGUI.java.