Java 7 for Absolute Beginners

(nextflipdebug5) #1
CHAPTER 7 ■ WRITING A USER INTERFACE

Figure 7-1. Simple SwingDemo application


All this program does is create and display an empty window. Let's look at how it does it, though. As
you can see, we first create a JFrame object, which defines the window. Then, we specify some attributes
for that window: size and whether to stop the application when the window closes. After setting those
attributes, we prepare the window for display with the pack and setVisible methods. The pack method
tells any Swing component that can have children to arrange its children within the component. The
setVisible method dictates whether a component is visible or hidden. Naturally, for an application's
main window, we want it to be visible. Hiding components can work well in some circumstances,
though. If you have a window that you want to show sometimes and not other times, leaving the window
in the set of windows and setting it to visible or hidden as needed uses a lot less overhead than creating it
from scratch every time, especially if the window needs to maintain some content along the way.
Notice the behavior of the main method. In particular, notice that it creates an instance of the class
that contains it. That's a common idiom for Swing programs. Otherwise, every method in the class must
be static, and that's a nuisance (and often just won't work). I prefer to create the instance as soon as
possible, to get it out of the way, so I put it in the main method. Other developers prefer to wait until at
least one Swing component requires an instance. That's largely a matter of style. The important thing is
that you'll almost always need to create an instance of your base class at some point.


■ Note A window is not a program. As the Jframe.EXIT_ON_CLOSE constant implies, an application does not


need to stop because all its windows have been closed. In fact, some applications never have a window in the first


place. Device drivers and services almost always run without showing a window.


Before we proceed, let's learn a bit more about JFrame. The first thing that trips up a lot of people is
that a JFrame goes into a separate component called .a content pane. You can get the content pane with
the getContentPane() method. You can also replace a content pane by calling setContentPane(). Any
class that extends Container can serve as a content pane. Swing developers often use a JPanel object
when they need to replace JFrame's content pane. You can swap sets of content by using setContentPane.
However, the card layout might work better for hiding and showing different sets of content.

Free download pdf