|
|
Using Swing Components |
Most Swing applications present their primary GUIs within aJFrame-- a window that is a top-level Swing container for applets and applications. A frame has decorations such as a border, a title, and buttons for closing and iconifying the frame. A typical program simply creates a frame, adds components to its content pane, and perhaps adds a menu bar. However, through its root pane,
JFrameprovides support for further customization.To make a window that's dependent on another window -- disappearing when the other window is iconified, for example -- use a dialog instead of a frame. To make a window that appears within another window, use an internal frame.
Here are two pictures of the same program, FrameDemo.java, running on different platforms. The program brings up a frame that contains a picture to look at.
Solaris Windows [PENDING: run this on
Windows and get a snapshot]
Note: The specific decorations on a frame are system-dependent. You cannot change the decorations on a frame.
Below is the entire
mainmethod fromFrameDemo.java.The code creates a frame with the title A Basic Frame and adds a window listener to it that exits the program when the user closes the frame.public static void main(String s[]) { JFrame frame = new JFrame("A Basic Frame"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); JLabel label = new JLabel("Something to look at", new ImageIcon("images/beach.gif"), JLabel.CENTER); label.setVerticalTextPosition(JLabel.TOP); label.setHorizontalTextPosition(JLabel.CENTER); frame.getContentPane().add(label, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); }The italic lines of code create the label that displays the text and image in the frame, which is essentially this program's GUI. You can use this program as a framework for your own programs-- just replace the italicized code with statements to create the components that make up your program's GUI.
The bold line adds the label to the frame's content pane. Refer to Adding Components to a Frame for further details and examples.
For a frame to appear on the screen, a program must either call
setSizeorpack, and then callsetVisible(true)or its equivalent,show. This program packs the frame and usessetVisible. Note that if any of the GUI is already visible, you should invokesetVisiblefrom the event dispatching thread. Refer to the Threads and Swing page.This code is typical of many programs and is the framework we used to create many of the examples for this lesson (including
GlassPaneDemo.java). Some examples in this lesson, such asTextFieldDemo.javaandTableDemo.java, subclassJFrameand instantiate the frame subclass instead ofJFrame. In these programs, the GUI is created in the constructor for the subclass. You might do this in your programs if you need to subclassJFramefor some reason.
JFrameitself is a subclass ofjava.awt.Frameto which it adds support for interposing input and painting behavior in front of the frame's children, placing children on different "layers", and for Swing menu bars. Generally speaking, you should use a
JFrameinstead of aFrame, for these reasons:
- To take advantage of new features provided by its root pane such as the glass pane and the layered pane.
JFramelets you customize window closing behavior by calling thesetDefaultCloseOperationmethod instead of writing a window listener.JFramesupports therevalidatemethod. [PENDING: link to where revalidate is discussed]- Swing menus work best in a
JFramedue to itssetJMenuBarmethod.- You must use a
JFramein an applet if the applet uses Swing components. Also, we recommend that you use aJFramein an application that uses Swing components, although it's not required.Adding Components to a Frame
As you saw inFrameDemo.java, to add components to aJFrame, you add them to the frame's content pane. Two common techniques are used to provide the components for a frame's content pane:
- Create an opaque container such as a
JPanelorJDesktopPane, add components to it, then use thesetContentPanemethod to make it the frame's content pane.
Note: Don't use non-opaque containers such asJScrollPane,JSplitPane, andJTabbedPaneas content panes. A non-opaque container results in messy repaints.
ListDialog.javauses this technique. The code creates a borderedJPanelto use as the frame's content pane. The panel contains two labels and a button.public static void main(String[] args) { JFrame f = new JFrame("Name That Baby"); //...create the labels and the button... JPanel contentPane = new JPanel(); f.setContentPane(contentPane); contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS)); contentPane.setBorder(BorderFactory.createEmptyBorder(20,20,20,20)); contentPane.add(intro); contentPane.add(name); contentPane.add(Box.createRigidArea(new Dimension(0,10))); contentPane.add(button); ... }- Use
getContentPaneto get the frame's content pane. Add components to the object returned.TableDemo.javauses this technique as shown here:The default layout manager for a frame's content pane ispublic class TableDemo extends JFrame { ... public TableDemo() { super("TableDemo"); ... JTable table = new JTable(myModel); ... JScrollPane scrollPane = new JScrollPane(table); getContentPane().add(scrollPane, BorderLayout.CENTER); ... } ... }BorderLayout. You can invoke thesetLayoutmethod on the content pane to change its layout manager.The Frame API
The following tables list the commonly usedJFrameconstructors and methods. Other methods you're likely to call are defined by theFrameand
Windowclasses and include
pack,setSize,show,hide,setVisible,setTitle, andgetTitle.Much of the operation of a frame is managed by other objects. For example, the interior of a frame is managed by its root pane, and the content pane contains the frame's GUI. Most of the API for using frames is related to Setting and Getting the Frame's Helper Objects.
The API for using frames falls into two categories:
Creating and Setting Up a Frame Method Purpose JFrame()
JFrame(String)Create a frame. The Stringargument provides a title for the frame.void setDefaultCloseOperation(int)
int getDefaultCloseOperation()Set or get the operation that occurs when the user pushes the close button on this frame. Possible choices are: These constants are defined in the
DO_NOTHING_ON_CLOSEHIDE_ON_CLOSE(the default)DISPOSE_ON_CLOSEWindowConstantsinterface.
Setting and Getting the Frame's Helper Objects Method Purpose void setContentPane(Container)
Container getContentPane()Set or get the frame's content pane. You can also set or get this through the frame's root pane. JRootPane createRootPane()
void setRootPane(JRootPane)
JRootPane getRootPane()Create, set, or get the frame's root pane. The root pane manages the interior of the frame including the content pane, the glass pane, and so on. void setJMenuBar(JMenuBar)
JMenuBar getJMenuBar()Set or get the frame's menu bar. You can also set or get this through the frame's root pane. void setGlassPane(Component)
Component getGlassPane()Set or get the frame's glass pane. You can also set or get this through the frame's root pane. void setLayeredPane(JLayeredPane)
JLayeredPane getLayeredPane()Set or get the frame's layered pane. You can also set or get this through the frame's root pane. Examples that Use Frames
This table lists examples that useJFrameand where those examples are described.
Example Where Described Notes FrameDemo.javaThis page. A basic frame with one component. TextFieldDemo.javaHow to Use Text Fields A subclass of JFrame.TableDemo.javaHow to Use Tables A subclass of JFramethat sets the frame's content pane.IconDemoApplet.javaHow to Use Icons Adds many components to the default content pane. LayeredPaneDemo.javaHow to Use Layered Panes Illustrates the use of a frame's layered pane. GlassPaneDemo.javaThe Glass Pane Illustrates the use of a frame's glass pane. MenuDemo.javaHow to Use Menus Shows how to put a JMenuBarin aJFrame.
|
|
Using Swing Components |