Organizing Components into Containers


Top-Level Containers

In order for an application to have a GUI, it must have, at minimum, a window visible on the computer screen. Most applications we deal with operate within the confines of a window. Windows look somewhat different from application to application and from platform to platform, but they basically amount to a rectangular section of the screen that is devoted to displaying output from a program and accepting input from the user. In Java, all types of windows are instances or descendants of java.awt.Window. A component is an instance or descendant of java.awt.Component and has a visible representation on the screen that may or may not respond to user input. Buttons, checkboxes and textareas are all familiar examples of components. A container is an instance or descendant of java.awt.Container and is nothing more than a component that can “contain” other components. Thus, a window is a component because it has a visible representation, and it is a container because it can contain other components. A window is a top-level container because it lives directly on the user’s desktop and cannot be contained by any other container. AWT offers three types of windows: Window, Frame and Dialog. Swing offers JWindow, JFrame and JDialog which extend respectively from their AWT counterparts as figure 12-4 illustrates.

image from book

 java.lang.Object    java.awt.Component       java.awt.Container          java.awt.Window             javax.swing.JWindow             java.awt.Frame                javax.swing.JFrame             java.awt.Dialog                javax.swing.JDialog

image from book

Figure 12-4: Top-Level Container Hierarchy

Window and JWindow

A window is a top-level container with no borders and no menubar. By itself, it isn’t much more than a rectangular section of screen that has been filled with a default background color and reserved for the use of the application. java.awt.Window is the root class of all top-level containers. JWindow is the Swing version of Window. Its looks are deceptively simple. In addition to other components not mentioned here, it contains a container called the content pane which is responsible for managing application specific content. When we put content ( buttons, textareas, pictures, etc. ) into a JWindow, we actually must add them to this content pane.

Figure 12-5 shows a screen shot of an empty JWindow; figure 12-6 shows the structure of the JWindow.

image from book
Figure 12-5: Screen Shot of an Empty JWindow

image from book
Figure 12-6: Structure of a JWindow

Frame and JFrame

A frame is usually what we think of when we say “window”. A frame typically includes a close-box, a title bar, a border than can be dragged to resize the frame, and an optional menu bar. JFrame is the Swing version of Frame. Similarly to JWindow, it has a content pane that is responsible for managing application-specific content. JFrame is the starting point for most GUI applications because of the window decorations it provides and because it isn’t dependent on the existence of a previously created window.

Figures 12-7 and 12-8 show an empty JFrame and its corresponding structure. Figures 12-9 and 12-10 show a JFrame with a menubar and its corresponding structure.

image from book
Figure 12-7: Screenshot of an Empty JFrame

image from book
Figure 12-8: Structure of an Empty JFrame

image from book
Figure 12-9: JFrame with Menubar

image from book
Figure 12-10: Structure of JFrame with Menubar

Dialog and JDialog

A dialog is a top-level window typically used to take some form of input from the user. Like a frame, it has a title and a border and an optional menubar. A dialog is very similar to a frame except that it is dependent on a parent frame or dialog. When its parent is hidden or closed, the dialog is hidden or closed. Also, a dialog can be modal which means that it can block user input to other parts of the application until the dialog is closed. JDialog is the Swing version of Dialog. JDialog has the same structure as a JFrame. Figure 12-11 shows a JDialog with a label and three buttons.

image from book
Figure 12-11: A JDialog with a Label and Three Buttons

Our First GUI Program

Let’s have some fun and write a GUI application. Our first GUI program will be “minimal” and “well-behaved”. By “minimal” I mean that it will display the simplest possible interface with which the user can interact. By “well-behaved” I mean that it will respond to user input in an appropriate manner. Compile and run the following code.

Example 12.1: chap12.TestFrame.java

image from book
 1      package  chap12; 2      import  javax.swing.JFrame; 3 4      public   class  TestFrame { 5        public   static   void  main(String[] arg) { 6          JFrame frame =  new  JFrame("Introduction to Swing"); 7          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 8          frame.setBounds(200, 100, 300, 200); 9          frame.setVisible( true ); 10       } 11     }
image from book

Use the following commands to compile and execute the example. From the directory containing the src folder:

         javac -d classes -sourcepath src src/chap12/TestFrame.java         java -cp classes chap12.TestFrame

Figure 12-12 shows the results of running this example. Check out the resulting application. Wow! We’ve written practically no code at all but look at all that has been provided to us. Click on the window decorations: the close box, and minimize and maximize buttons. Resize the window. This window has the same behavior in all respects as the standard window on your computer no matter the operating system because it is a standard operating system window.

image from book
Figure 12-12: TestFrame GUI

Explanation of the Code

On line 6 we used a JFrame because it provides us with the operating system’s standard decorated window, and because it fully supports Swing’s component architecture. We passed a String parameter into the constructor so the JFrame could display a title in its title bar. A well-behaved program usually displays titles on the windows it creates to distinguish them from windows created by other applications.

Since our program only creates one window, quitting the application when the user attempts to close the window is the expected behavior. For this reason we called frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) on line 7. The available options for the default bahavior are the following:

  • EXIT_ON_CLOSE - quits the application;

  • DO_NOTHING_ON_CLOSE - does nothing;

  • HIDE_ON_CLOSE - makes the window invisible but keeps it in memory for redisplay;

  • DISPOSE_ON_CLOSE - destroys the window and frees up associated memory.

You can take some time here to experiment with the code. Change line 7 to use DO_NOTHING_ON_CLOSE, compile and run the program. Now change it to use HIDE_ON_CLOSE. Do you notice the difference in behavior between HIDE_ON_CLOSE and EXIT_ON_CLOSE?

On line 8 our well-behaved program sets the bounds of the window rather than leaving it to platform defaults. JFrame inherits the setBounds() method from java.awt.Component (see table 12-1). The parameters to the setBounds() method are in pixels and are interpreted in the coordinate system of the component’s container, which is in this case the computer screen. The width and height parameters include the frame’s border decorations, so the content pane is somewhat smaller than its total bounds. Comment out line 8, compile and run again to see the results. Change the bounds parameters, compile and run. What happens if you give a negative value for one of the parameters, for instance? What happens if you set the width and height to zero?

Table 12-1: java.awt.Component.setBounds() Methods

Method Name & Purpose

public void setBounds(int x, int y, int width, int height)

Sets the location and size of the component.

public void setBounds(Rectangle r)

Sets the location and size of the component to match the specified Rectangle.

On line 9 we called JFrame.setVisible(true) so that the window would be visible. Simple enough! Comment out this line, compile and run the program again to see ( or not see ) the results.

Top-Level Containers API

OK, that’s enough fun for now. It’s time to look at the API for the top-level containers. While it is generally my intention to encourage you to consult the javadocs, I couldn’t in good conscience send you there on your own right now without some help. If you look at the javadocs for java.awt.Window, for example, you will find a mind-numbing assortment of methods, many of which have no relevance to a beginner. Indeed, some of them are so technical that you might never need them, but they’re there just in case. If I counted correctly, Window defines or overrides 51 different methods. But remember that Window extends from Container, which extends from Component, which extends from Object. From Container it inherits 59 methods, from Component it inherits 161, and from Object it inherits 9. Adding these numbers together we get 51 + 59 + 161 + 9 = 280 methods available to Window! This number is slightly inflated because it double-counts overridden methods, but it does highlight the enormity of the AWT/Swing API. Unfortunately, the javadocs don’t organize methods by programmer level (novice/expert), area of functionality, or even relative importance. They arrange them alphabetically. In this chapter, we will only cover only 30 of the top-level container methods, but that will be enough to get you pretty far. After the next chapter adds a few event handling methods, you will have possibly all you’ll ever need to create a great variety of complex GUI applications.

Top-Level Container Constructors

There are many constructors for top-level containers depending on which type you are creating. Most of them are listed in table 12-2. Take a look at them now.

Table 12-2: Top-Level Containers Constructor Chart

Top-Level Containers Constructor Chart

Window types: W = Window, F = Frame, D = Dialog, JW = JWindow, JF = JFrame, JD = JDialog

Constructor Parameters

W

F

D

JW

JF

JD

() [no parameters]

Frame and JFrame : Constructs an initially invisible frame.

JWindow: Constructs an initially invisible window.

JDialog: Constructs an initially invisible non-modal dialog.

   

(Window owner)

Constructs a new invisible window with the specified Window as its owner.

     

(Frame owner)

Constructs a new invisible window or dialog with the specified Frame as its owner.

   

(Dialog owner)

Constructs an initially invisible, non-modal dialog without a title and with the specified owner dialog.

     

(String title)

Constructs a new, initially invisible frame with the specified title.

      

(Frame owner, String title)

Constructs an initially invisible, non-modal dialog with the specified owner frame and title.

     

(Dialog owner, String title)

Constructs an initially invisible, non-modal dialog with the specified owner dialog and title.

     

(Frame owner, boolean modal)

Constructs an initially invisible dialog without a title and with the specified owner frame and modality.

     

(Dialog owner, boolean modal)

Constructs an initially invisible dialog without a title and with the specified owner dialog and modality.

     

(Frame owner, String title, boolean modal)

Constructs an initially invisible dialog with the specified owner frame, title, and modality.

     

From this table we can make several observations:

  • Observation 1: Window, JWindow, Dialog and JDialog offer constructors that take owner parameters. Windows that are owned by other windows are dependent on their owner windows. They are minimized when their owner is minimized, they are closed when their owner is closed, and they are hidden or shown when their owner is hidden or shown.

  • Observation 2: Frame and JFrame don’t offer constructors that take an owner parameter. Actually, they are the only top-level containers whose construction doesn’t require the existence of a previously constructed top-level container.

Dialogue with a Skeptic

  • Skeptic: Wait a minute! I’m looking right at the javadocs and I see that JWindow and JDialog offer constructors that don’t require an owner parameter. Doesn’t that mean that their construction doesn’t require the existence of a previously constructed top-level container either?

  • Author: Yes, the javadocs do seem to suggest that, but it’s not true. If you don’t pass an owner into a JWindow or JDialog constructor, or if you pass an owner that is null, Swing assigns them an owner Frame courtesy of javax.swing.SwingUtilities.getSharedOwnerFrame().

  • Skeptic: [Quickly looks up SwingUtilities in the javadocs. Not finding the method getSharedOwnerFrame, he returns a bit suspicious.] What method did you say? I didn’t find it in the javadocs.

  • Author: [Good-natured chuckle] Oh, it’s not in the javadocs because it’s package private, but you can find the actual source code in the “src.zip” file which should be located right inside your Java installation directory. Look at the constructors in javax/swing/JWindow.java and you will see references to SwingUtilities.getSharedOwnerFrame(). Then if you look at the source for javax/swing/ SwingUtilities.java —

  • Skeptic: Wait a minute while I find it!

  • Author: I’ll wait.

  • Skeptic: [After navigating his computer’s file system, he finds the Java installation directory and opens the “src.zip” file] Ok, I see the “SwingUtilities.java” file. [Opening up “SwingUtilities.java” in an editor and scanning the file] Now I’ve found the getSharedOwnerFrame method! [Reading]static Frame getSharedOwnerFrame() throws HeadlessException”.

  • Author: Great! Just look at the comments for now. What do they say?

  • Skeptic: [Reading]Returns a toolkit-private, shared, invisible Frame to be the owner for JDialogs and JWindows created with null owners.

  • Author: Very good! For now we’ll continue with our observations. But feel free to browse any of the source code on your own later. It can often be very helpful.

  • Observation 3: Only Frame, JFrame, Dialog and JDialog constructors offer a title parameter. This makes sense since they’re the only ones with title bars.

  • Observation 4: Only Dialog and JDialog offer the modal parameter. If the modal parameter is true, the dialog will block user input to the owner window until the dialog has been closed. If it’s false, input to the owner window will not be blocked.

  • Observation 5: All constructors create initially invisible windows. You must call setVisible(true) or show() to make the window visible.

Top-Level Container Methods

Read through tables 12-3 through 12-7 to familiarize yourself with many of the top-level container methods. Note that the methods in these tables do not include the many methods inherited from Container from which, as you may remember, all window types extend.

Table 12-3: Methods Available to All Descendants of Window

Method Name and Purpose

public void show()

Makes the window visible.

public void hide()

Hide this window, its subcomponents, and all of its owned children.

public boolean isShowing()

Checks if this window is showing on the screen.

public void toFront()

If this window is visible, brings this window to the front and may make it the focused window.

public void toBack()

If this window is visible, sends this window to the back and may cause it to lose focus or activation if it is the focused or active window.

public boolean isFocused()

Returns whether this window is focused.

public boolean isActive()

Returns whether this window is active. Only frames and dialogs may be active. The active window is always either the focused window, or the first frame or dialog that is an owner of the focused window.

public void setLocationRelativeTo(Component)

Sets the location of the window relative to the specified component.

public void pack()

Causes this window to be sized to fit the preferred size and layouts of its subcomponents.

public String getWarningString()

Gets the warning string that is displayed with this window. You will see a warning string if the window is considered insecure. This may happen, for instance, if the window is created by an Applet running in a browser.

public Window getOwner()

Returns the owner of this window.

public Window[] getOwnedWindows()

Return an array containing all the windows this window currently owns.

public void dispose()

Releases all of the native screen resources used by this window, its subcomponents, and all of its owned children.

Table 12-4: Methods Available to Frame, JFrame, Dialog, JDialog Only

Method Name and Purpose

public String getTitle()

Gets the title of the frame or dialog.

public void setTitle(String title)

Sets the title for this frame or dialog to the specified string.

public boolean isResizable()

Indicates whether this frame or dialog is resizable by the user.

public void setResizable(boolean resizable) Sets whether this frame or dialog is resizable by the user.

public boolean isUndecorated()

Indicates whether this frame or dialog is undecorated.

public void setUndecorated(boolean undecorated)

Disables or enables decorations for this frame or dialog.

Table 12-5: Methods Available to Frame, JFrame Only

Method Name and Purpose

public static Frame[] getFrames()

Returns an array containing all Frames created by the application.

public int getExtendedState()

Gets the state of this frame represented as a bitwise mask. Any of the following may be bitwise or’d together: NORMAL, ICONIFIED, MAXIMIZED_HORIZ, MAXIMIZED_VERT and MAXIMIZED_BOTH.

public void setExtendedState(int state)

Sets the state of this frame represented as a bitwise mask. (See getExtendedState() above).

public Image getIconImage()

Gets the image to be displayed in the minimized icon for this frame. This is also the image displayed in the top-left corner of the title bar.

public void setIconImage(Image image)

Sets the image to be displayed in the minimized icon for this frame. (See getIconImage() above).

Table 12-6: Methods Available to JWindow, JFrame, JDialog Only

Method Name and Purpose

public Container getContentPane()

Returns the Container which is the content pane for this window. Components added to any Swing top-level container must be added to the container’s content pane. Although, as descendants of Container they inherit all of the add methods, Swing top-level containers have overridden these methods to throw a runtime exception. In other words, your code would compile but not run. So remember: when using JWindow, JFrame and JDialog add components to the content pane!

public void setContentPane(Container contentPane)

Sets the content pane property for this window.

Table 12-7: Methods Available to JFrame, JDialog Only

Method Name and Purpose

public JMenuBar getJMenuBar()

Returns the menubar set on this frame or dialog.

public void setJMenuBar(JMenuBar menu)

Sets the menubar for this frame or dialog.

public int getDefaultCloseOperation()

Returns the operation which occurs when the user initiates a "close" on this frame or dialog. This will either be DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE, DISPOSE_ON_CLOSE or EXIT_ON_CLOSE.

public void setDefaultCloseOperation(int operation)

Sets the operation which will happen by default when the user initiates a "close" on this frame or dialog. (See getDefault-CloseOperation() above).

Quick Review

A component is any GUI object that has a visible representation on the screen. A container is a component that can “contain” other components. A top-level container is a container that exists on the computer screen and can’t be contained by another container. Java GUI applications must start with a top-level container otherwise known as a window. There are three types of windows: Window, Frame, Dialog. Their Swing counterparts are JWindow, JFrame and JDialog. All Swing top-level containers have a content pane to which GUI components must be added. JFrame is comprised of a title bar, border, optional menubar and a content pane. Most Swing applications will begin with a JFrame since it isn’t dependent on the existence of a previously created window.




Java For Artists(c) The Art, Philosophy, and Science of Object-Oriented Programming
Java For Artists: The Art, Philosophy, And Science Of Object-Oriented Programming
ISBN: 1932504052
EAN: 2147483647
Year: 2007
Pages: 452

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