Sie sind auf Seite 1von 67

Swing Set

Theparit Peerasathien
Features of the Java Foundation
New GUI called swing set
Graphic API called 2D graphics
Accessibility API
Drag and Drop API
Heavyweights & Lightweights
Heavyweight components (peer)
Associated with its own native screen
Connect with JVM & API

Top-level swing: JFrame, JDialog, JApplet

Heavyweights & Lightweights
Lightweight components
borrows" the screen resource of an
no native resource of its own

All Swing set except Top-level swing

How to use Components
Top-level component
is a root of every
All Swing programs
have at least one
Top-level component
Add Lightweight
component to
content Panes

Swing Set
Top-Level Containrs
General-Purpose Containers
Special-Purpose Containers
Basic Controls
Uneditable Information Displays
Interactive Displays of Highly
Formatted Information
Top-level Components
Types of top-level containers

Top-Level Component
Add() components to Content pane
setLayout() content pane
Calling by
public Container getContentPane();
support for adding a menu bar
need to use a content pane


Window with border, title and buttons

Making frames
JFrame frame = new JFrame();
Or a extend JFrame class (often better code this way).
Style defined with
Sample code
Specifying Window Decorations
Specifying Window Decorations
Responding to Window-Closing
By default, when the user closes a frame
onscreen, the frame is only hidden.
register a window listener that handles
window-closing events
Use setDefaultCloseOperation method
a subclass of java.applet.Applet
top-level Swing container
Swing applet has a root pane - support for
adding a menu bar
has a single content pane.
add components to a Swing applet's
content pane, not directly to the applet
set the layout manager on a Swing
applet's content pane, not directly on the
default layout manager for a Swing
applet's content pane is BorderLayout
should not put painting code directly in a
JApplet object
import javax.swing.JApplet;
import java.awt.*;
public class JAppletTest extends JApplet {
public void int() {
Container cp = getCntentPane();
cp.setLayout (new FlowLayput);
cp.add(new JLabel(Hello);

windows that are more limited than frames
To create simple, standard dialogs, you
use the JOptionPane class.
The ProgressMonitor class can put up a
dialog that shows the progress of an
JColorChooser and JFileChooser supply
standard dialogs for Color chooser and
File Chooser
can create and customize several different
kinds of dialogs
provides support for laying out standard
dialogs, providing icons, specifying the
dialog's title and text, and customizing the
button text

Sample JDialog
//default title and icon
JOptionPane.showMessageDialog(frame, "Eggs
aren't supposed to be green.");

//custom title, warning icon
JOptionPane.showMessageDialog(frame, "Eggs
aren't supposed to be green.", "Inane warning",

//custom title, custom icon
JOptionPane.showMessageDialog(frame, "Eggs
aren't supposed to be green.", "Inane custom
Swing Set
Top-Level Containrs
General-Purpose Containers
Special-Purpose Containers
Basic Controls
Uneditable Information Displays
Interactive Displays of Highly
Formatted Information
Except top-level container, All Swing
components names begin with J
descend from the JComponent class
Example JPanel, JButton, JTable
Except JFrame JDialog (Top-level
JComponent Features
Tool tips
- When the cursor pauses over the component,
the specified string is displayed in a small window
Painting and Border
allows you to specify the border that a component displays
around its edges
Look and feel
has a corresponding ComponentUI
Custom properties
- associate one or more properties (name/object pairs)
with any JComponent

JComponent Features
Support for Layout
setter methods setPreferredSize, setMinimumSize,
setMaximumSize, setAlignmentX, and setAlignmentY
Support drag and Drop
provides API to set a component's transfer handler, which is
the basis for Swing's drag and drop support
Double buffering
Double buffering smooths on-screen painting
Key Bindings
components react when the user presses a key on the
Example when a button has the focus, typing the Space key is
equivalent to a mouse click on the the button

General-Purpose Containers
Scroll pane
Split pane
Tabbed pane
Tool bar
JPanel class provides general-purpose
containers for lightweight components
By default, panels don't paint anything
except for their background
customize their painting
In many look and feels (but not GTK+),
panels are opaque by default
You can change a panel's transparency
by invoking setOpaque

Setting the Layout Manager
By default, a panel's layout manager is
an instance of FlowLayout
JPanel p = new JPanel(new

JPanel p = new JPanel(); p.setLayout(new
BoxLayout(p, BoxLayout.PAGE_AXIS));
Adding Components


Swing Set
Top-Level Containrs
General-Purpose Containers
Special-Purpose Containers
Basic Controls
Uneditable Information Displays
Interactive Displays of Highly
Formatted Information
Special-Purpose Containers
Intermediate containers that play specific
roles in the UI.
Internal Frame
Layered Pane
Root Pane

Special-Purpose Containers
Internal Frames
JInternalFrame class you can display a
JFrame-like window within another window
add internal frames to a desktop pane
The desktop pane is an instance of

...//In the constructor of InternalFrameDemo, a JFrame subclass:
desktop = new JDesktopPane(); createFrame();
//Create first window setContentPane(desktop);
//Make dragging a little faster but perhaps uglier.

protected void createFrame() {
MyInternalFrame frame = new MyInternalFrame();
desktop.add(frame); try {
} catch (java.beans.PropertyVetoException e) {}

Internal Frames vs. Regular Frames
internal frames is similar in many ways to the code for
using regular Swing frames
internal frames have root panes
also provides other API, such as pack

Internal frames aren't windows or top-level containers
You can programatically iconify or maximize an
internal frame. You can also specify what icon goes in
the internal frame's title bar. You can even specify
whether the internal frame has the window decorations
to support resizing, iconifying, closing, and
Layered Panes
Swing container that provides a third
dimension for positioning components
specify its depth as an integer. The
higher the number, the higher the depth.
If components overlap, components at a
higher depth are drawn on top of
components at a lower depth
Layered Panes
Example Code
Adding Components and Setting
Component Depth
Position Depth
Positions are specified with an int between -1
and (n - 1), where n is number of component
the smaller the position number, the higher
the component within its depth exception (-1)
is deepest too
Component's position change
Layer pane
Root Panes
don't directly create a JRootPane object
instantiate JInternalFrame or one of the
top-level Swing containers
Use Top-Level Container
getting the content pane
setting its layout manager
adding Swing components

four parts of root pane
The glass pane
completely transparent unless you implement the glass pane's
paintComponent method so that it does something, and it intercepts
input events for the root pane.
The layered pane
Serves to position its contents, which consist of the content pane and
the optional menu bar. Can also hold other components in a
specified Z order..
The content pane
The container of the root pane's visible components, excluding the
menu bar..
The optional menu bar
The home for the root pane's container's menus. If the container has
a menu bar, you generally use the container's setJMenuBar method
to put the menu bar in the appropriate place.
The Glass Pane
is useful when you want to be able to catch
events or paint over an area that already
contains one or more components
It contains a check box that lets you set
whether the glass pane is "visible" whether
it can get events and paint itself onscreen.
When the glass pane is visible, it blocks all
input events from reaching the components
Sample Code
Swing Set
Top-Level Containrs
General-Purpose Containers
Special-Purpose Containers
Basic Controls
Uneditable Information Displays
Interactive Displays of Highly
Formatted Information
Basic Control Component
Atomic components that exist primarily to
get input from the user
show simple state
Basic Control Component
Swing Set
Top-Level Containrs
General-Purpose Containers
Special-Purpose Containers
Basic Controls
Uneditable Information Displays
Interactive Displays of Highly
Formatted Information
Uneditable Information Displays
Atomic components that exist solely to give
the user information
Swing Set
Top-Level Containrs
General-Purpose Containers
Special-Purpose Containers
Basic Controls
Uneditable Information Displays
Interactive Displays of Highly
Formatted Information
Interactive Displays of Highly
Formatted Information
Atomic components that display highly
formatted information
Swing Set Getting Start
Model Delegate Architecture
MVC architecture is a well-known design
for GUI objects
Classic MVC architecture divides each
component into three parts: a model, a
view, and a controller

Model Delegate Architecture

The model passes its data to view for
The View determines which events are passed
to the controller
The Controller updates the model bases on the
events received

Swing's MVC design
the model part of a component is treated as a
separate element just as the MVC design does
But Swing collapses the view and controller parts
of each component into a single UI (user-interface)
Why ?
The view and controller parts of a
traditional MVC-based component
require a tight coupling that is sometimes
difficult to achieve in practical terms
For example: Traditional MVC
architecture makes it very hard to create
a generic controller that doesn't know at
design time what kind of view will
eventually be used to display it.
How the Swing program works
making lightweight and heavyweight
components work together
Add Lightweight components to
Heavyweight component
To obtain a content pane, you call a
Container method named
Creating GUI components
Laying out an interface
Laying out an interface
the first code sequence constructs a JToggleButton object, sets
its initial label and its position, and then adds an ActionListener to
monitor and handle events
The second sequence uses Swing's BoxLayout manager to lay
out the SwingingApplet program's GUI interface. It obtains a
Container object named contentPane by calling the
To set the center alignment of its two buttons, the program calls
the setAlignmentX() methods. The applet doesn't have to call
Event: The heart of the program

Event: The heart of the program
The actionPerformed() method is an
event handler built around an if . . . else
It repeatedly checks to see if the user
has clicked the Swing!/Stop! toggle
Sample Major Change in Swing JDK
Improve default look and feel of Swing
If you use the Java look and feel your application
will automatically get a new look, called Ocean
Swing Skins Look and Feel
Alloy Look and Feel and L2F's Skinnable Look and

Implement context popup menus for components
added a mechanism to take care of registering the
appropriate listeners and key bindings to