Beruflich Dokumente
Kultur Dokumente
#95
Get More Refcardz! Visit refcardz.com
n
Swing Components
n
The Anatomy of an SWT Application
n
SWT Components
n
Event Handling and more... By James Sugrue
For standalone Java desktop application, developers have two All Swing components are derived from JComponent, which deals
main options. You can use Java Swing, built into the JDK, or with the pluggable look & feel, keystroke handling, action object,
you can use the Standard Widget Toolkit (SWT) from Eclipse. borders and accessibility.
Both approaches share some commonality, but each has its own
A typical Swing application will consist of a main window, with a
advantages and methods. This DZone Refcard provides a reference
menu-bar, toolbar and contents. The main shell for the application
on how to use both technologies; the first half of the Refcard will
is represented as a JFrame. Within the JFrame, an instance of
cover Swing, with SWT forming the second �half.
JRootPane acts as a container for all other components in
the frame.
JAVA SWING - A HISTORY
Before Swing, the only option that Java GUI developers had
was to use AWT (Abstract Widget Toolkit). However, because
of limitations in AWT, such as the number of components and
www.dzone.com
javax.swing.plaf.synth Synth is a skinnable look and feel in which all painting is delegated.
javax.swing.text Provides classes and interfaces that deal with editable and noneditable
text components.
javax.swing.text.html Provides the class HTMLEditorKit and supporting classes for creating
HTML text editors.
javax.swing.text.html.parser Provides the default HTML parser, along with support classes.
javax.swing.JButton
javax.swing.JCheckBox
javax.swing.JComboBox
javax.swing.JSlider
javax.swing.JSpinner
javax.swing.JTextField
javax.swing.JToolbar
Container Purpose
fill Used to specify how to fill any unused space in the grid cell. Options are NONE
Containment (default), HORIZONTAL, VERTICAL or BOTH.
Each component can only be contained once. If you add
Hot a component to another container, after adding it to a
ipadx, ipady Specifies how many pixels to pad around the components minimum size in the
x or y direction.
Tip different one previously, it will be removed from the insets Specifies how much should be added to the external padding of the component
previous container, and only added to the last one. out to the edges of its display area.
anchor Specifies where the component should be positioned in its display area.
weightx, Determines how to distribute space around a component, for resizing behaviour.
CORE LAYOUT MANAGERS weighty
All layout managers implement one of two interfaces: java. EVENT HANDLING
awt.LayoutManager or its subclass, java.awt.LayoutManager2.
LayoutManager provides methods that give a straight-forward, Standard click events on Swing components are handled
organized means of managing component positions and sizes in using the java.awt.event.ActionListener interface.
a container. LayoutManager2 enhances this by adding methods Implemented action handlers need to implement the public
intended to aid in managing component positions and sizes using voidactionPerformed(ActionEvent e), provided the component
constraints-based objects. Constraints-based objects store position has registered the action listener using the addActionListener()
and sizing information about one component and implementations method.
of LayoutManager2 normally store one constraints-based object
per component. Three interfaces are provided to handle mouse events on
components:
java.awt.FlowLayout
A flow layout arranges components in a directional flow Interface Methods
one after the other, moving onto a new line when no more java.awt.event.MouseListener public void mouseClicked(MouseEvent e);
public void mousePressed(MouseEvent e);
components fit on the current line. Direction is determined by public void mouseReleased(MouseEvent e);
the container’s componentOrientation property and may be public void mouseEntered(MouseEvent e);
public void mouseExited(MouseEvent e);
one of two values: ComponentOrientation.LEFT_TO_RIGHT or
java.awt.event.MouseWheelListener public void mouseWheelMoved(MouseWheelEvent e);
ComponentOrientation.RIGHT_TO_LEFT
java.awt.event.MouseMotionListener public void mouseDragged(MouseEvent e)
Flow layout is the default layout manager for AWT and public void mouseMoved(MouseEvent e);
Swing components.
Alternatively, you can extend the java.awt.event.MouseAdapter
java.awt.GridLayout class, which packages all three interfaces into a single abstract
GridLayout lays out a container’s components in a rectangular class to make it easier to handle particular mouse events.
grid. The container is divided into equal-sized rectangles, and one
component is placed in each rectangle. Typically, a GridLayout is
Attaching Mouse Listeners
Mouse listeners can be added to your component by
constructed by specifying the number of rows and columns.
simply using the appropriate method (addMouseListener,
java.awt.BorderLayout addMouseWheelListener, addMouseMotionListener).
BorderLayout lays out the components in five regions: NORTH,
SOUTH, EAST, WEST and CENTER. As each component is added THREADING ISSUES IN SWING
to a container with a border layout, the location is specified similar
to: container.add(component, BorderLayout.CENTER); Time consuming tasks should not be run on the event dispatch
java.awt.CardLayout thread, as this will cause the application to become unresponsive.
Additionally, any components accessed should only be accessed
CardLayout acts as an organisation of stacked components on
through the event dispatch thread.
a container, with only one card being visible at a time. The first
component added is the visible component when the container is SwingWorker is designed for situations where you need to have a
first displayed. Methods exist to go through the stack sequentially long running task run in a background thread and provide updates
to the UI either when done, or while processing. Subclasses of
or to access a particular card.
SwingWorker must implement the doInBackground() method to
javax.swing.BoxLayout perform background computation.
BoxLayout allows multiple components to be laid out vertically
(Y_AXIS) or horizontally (X_AXIS). Components do not wrap, so ECLIPSE STANDARD WIDGET TOOLKIT - A HISTORY
when the frame is resized the components remain in their initial
arrangement. Components are arranged in the order that they are The Standard Widget Toolkit (SWT) is a widget toolkit that
added to the layout manager. provides both a portable API and tight integration with the
underlying native OS GUI platform. SWT defines a common API
java.awt.GridBagLayout provided on all supported platforms, allowing the toolkit to take
GridBagLayout is the most flexible layout manager, maintaining on the look & feel of the underlying native widgets. JFace provides
a dynamic, rectangular grid of cells. Each component a higher level abstraction over SWT, in a similar way to Swing and
can occupy one or more cells, and has an instance of AWT. However, most controls are available in SWT, with JFace
GridBagConstraints to specify how a component should be providing viewers and actions.
displayed in its display area.
CORE PACKAGES
The following table illustrates the options in GridBagConstraints:
Variable Name Use package Purpose
gridx, gridy Specifies the location on the grid to place the component, with gridx=0, gridy=0 org.eclipse.swt Provides the class SWT which contains all of the constants used by SWT
as the top left hand corner. as well as a small selection of error handling routines and queries such as
getPlatform and getVersion.
gridwidth, Specifies the number of rows, or columns that will be used for a components
gridheight display area. The default value is 1. org.eclipse.swt.accessibility Contains the classes that support platform accessibility.
org.eclipse.swt.awt Contains the SWT_AWT bridge, allowing AWT components to be controls, similar to a JPanel in Swing. Composite is the super class
embedded in SWT components and vice versa. of all composites, and can also be used directly.
org.eclipse.swt.browser Provides the classes to implement the browser user interface metaphor. org.eclipse.swt.widgets.Dialog
org.eclipse.swt.custom Contains the custom widgets which were written to provide the standard SWT also provides a Dialog class, which should be modal with a
look and feel of the Eclipse platform. Shell as its parent.
org.eclipse.swt.dnd Contains the classes which make up the public API of the SWT Drag and
Drop support.
SWT COMPONENTS - BASIC CONTROLS
org.eclipse.swt.events Provides the typed events and listener interfaces.
org.eclipse.swt.graphics Provides the classes which implement points, rectangles, regions, colors,
cursors, fonts, graphics contexts (that is, GCs) where most of the primitive Components Appearance (various platforms)
drawing operations are implemented.
org.eclipse.swt.browser.Browser
org.eclipse.swt.layout Contains several standard layout classes which provide automated
positioning and sizing support for SWT widgets.
org.eclipse.swt.opengl Contains widgets for integrating OpenGL graphics into SWT applications.
org.eclipse.swt.widgets.Button
org.eclipse.swt.printing Contains the classes which provide printing support for SWT.
org.eclipse.swt.program Contains class Program which provides access to facilities for discovering
operating system specific aspects of external program launching.
org.eclipse.swt.widgets Contains the classes which make up the public SWT widget API as well as
the related public support classes.
org.eclipse.swt.widgets.Shell
The Shell is the main window, and parent container of all other
widgets in an SWT application.
org.eclipse.swt.widgets.Composite
The Composite is a widget that can contain other composites or
horizontalIndent, The number of pixels to move in from the left or the top
verticalIndent of the cell.
org.eclipse.swt.custom.StyledText
horizontalSpan, verticalSpan The number of rows or columns that the widget will occupy.
org.eclipse.swt.layout.FormLayout
org.eclipse.swt.widgets.Table FormLayout positions children of a composite control by using
FormAttachments to optionally configure the left, top, right
and bottom edges of each child. Each child of a composite
using FormLayout needs to have a FormData object with a
org.eclipse.swt.widgets.Text FormAttachment.
Each side of a child control can be attached to a position in the
parent composite, or to other controls within the Composite by
creating instances of FormAttachment and setting them into the
top, bottom, left, and right fields of the child’s FormData. If a side
is not given an attachment, it is defined as not being attached to
org.eclipse.swt.widgets.ToolBar
anything, causing the child to remain at its preferred size.
If a child is given no attachment on either the left or the right or
org.eclipse.swt.widgets.Tray top or bottom, it is automatically attached to the left and top of
the composite respectively.
SWT provides two ways of handling events: using the built in typed
listeners, or using un-typed listeners which provides a framework
for you to create your own listeners.
CORE LAYOUT MANAGERS Un-typed Listeners
Creating un-typed listeners in SWT involves three classes from the
Just as in Swing, SWT provides a number of core layout managers, org.eclipse.swt.widgets package:
as well as providing the opportunity to create your own custom
Event This class provides a description of the event that has been triggered, including
layout from the org.eclipse.swt.layout.Layout base class. fields for type, widget and time
org.eclipse.swt.layout.FillLayout Listener The listener interface needs to be implemented by any class that listens for events.
The interface simply defines a handleEvent(Event e) method in order to do this.
FillLayout lays all widgets in a single continuous row or column. All
widgets are forced to be the same size in this layout. Unlike Swing’s Widget Each widget object has an addListener(int eventType, Listener handler) method
with a corresponding removeListener method.
FlowLayout, FillLayout does not wrap, but you can specify margins
and spacing. FillLayout is useful when a Composite only has one The addListener method accepts an eventType method. The
child, as it can cause the child of the composite to fill the shell. following table lists out the possible values for this field:
FillLayout fillLayout = new FillLayout(SWT.VERTICAL); shell.setLayout(fillLayout);
Event Type Description
allows components to wrap and also provides margins and spacing. SWT.Close A Shell is about to close
Rather than all components being the same size, each control can SWT.DefaultSelection The user selects an item by invoking a default selection action.
have its own parameters using the RowData object. A control can SWT.Dispose A widget is about to be disposed.
use this object through its setLayoutData method.
SWT.DragDetect The user has initiated a possible drag operation.
org.eclipse.swt.layout.GridLayout SWT.EraseItem A TableItem or TreeItem is about to have its background drawn.
The most flexible layout manager in SWT is GridLayout, which lays
SWT.Expand, SWT.Collapse An item in a Tree is expanded or collapsed.
components out in a grid formation. Each control that is placed
SWT.PaintItem A TableItem or TreeItem is about to have its foreground drawn. Hot SWT will trigger an SWTException for any calls made from a
SWT.Selection The user selects an item in the control.
Tip non-UI thread that must be made from the UI thread.
SWT.SetData Data needs to be set on a TableItem when using a virtual table.
#82
CONTENTS INCLUDE:
■
■
About Cloud Computing
Usage Scenarios Getting Started with
Aldon Cloud#64Computing
■
Underlying Concepts
Cost
by...
■
Upcoming Refcardz
youTechnologies ®
■
Data
t toTier
brough Comply.
borate.
Platform Management and more...
■
Chan
ge. Colla By Daniel Rubio
tion:
dz. com
tegra ternvasll
ABOUT CLOUD COMPUTING one time events. TEN TS
INC ■
HTML LUD E:
us Ind Anti-PPaat
Basics
Automated growthHTM
ref car
nuorn
■
Valid
ation one time events, cloud ML
connected to what is now deemed the ‘cloud’. Having the capability to support
Java EE Security
Usef
Du
ti
■
ul M.
computing platforms alsoulfacilitate
#84
Open the gradual growth curves
n an
Page Source
o
■
s
Vis it
C
faced by web applications. Tools
Core
By Key ■
Elem
Patte
has changed substantially in recent years, especially with Structur
E: al Elem ents
INC LUD gration the entrance of service providers like Amazon, Google and Large scale growth scenarios involvingents
specialized
NTS and mor equipment
rdz !
HTML
CO NTE Microsoft. es e... away by
(e.g. load balancers and clusters) are all but abstracted
Continu at Every e chang
m
About ns to isolat
relying on a cloud computing platform’s technology.
Software i-patter
space
■
n
Re fca
e Work
Build
riptio
and Ant
Desc
These companies have a Privat
are in long deployed
trol repos
itory
webmana applications
ge HTM
L BAS
■
Build
re
Buil Repo
This Refcard active
will introduce are within
to you to cloud riente computing, with an
d units
RATION etc. Some platforms ram support large grapRDBMS deployments.
■
The src
dy Ha
softw
e ine loping and Java s written in hical on of
INTEG attribute
task-o it all
softwar emphasis onDeve es by
Mainl these
ines providers, so youComm can better understand
also rece JavaScri user interfac web develop and the rris
Vis it
Network Security
codel chang desc
INUOU ding Task Level as the
e code
ww w.dzone.com
Label
Build
manu
al
d tool
depe deplo t need but as if
eve , a ) stalle the same nmen for stan overlap uen
(i.e. , inef Build t, use target enviro Amazon EC2: Industry standard it has
software and uagvirtualization ine. HTM , so <a>< tly are) nest
with terns problem ce pre-in whether dards
ated b></
ory. ns (i.e. Autom Redu ymen
has bec become e with a> is
via pat ticular d deploEAR) in each very little L
Maven 3
reposit -patter s that Pay only cieswhat you consume
tagge or Amazon’s cloud you cho platform
computing
the curr isome
heavily based moron fine. b></ ed insid
lained ) and anti the par solution duce nden For each (e.g. WAR es t
ent stan ose to writ more e imp a></ e
not lega each othe
x” b> is
be exp text to “fi are al Depeapplication deployment
Web ge until t a
librarifew years agonmen
t enviro was similar that will softwaredard
industry standard and virtualization app
e HTM technology.
orta nt,
tterns to pro Minim packa nden
Mo re
CI can ticular con used can rity all depe all targe
s will L or XHT arent. Reg the HTM l, but r. Tags
etimes Anti-pa they
tend
es, but to most phone services:
y Integ alizeplans with le that
late fialloted resources, ts with an and XHT simplify all help ML, und ardless
L VS
XHTM <a><
in a par hes som
Centr
end,
Binar
pro cess. the practic enti ng incurred costgeme
nt
whether e a single
such
temp
resources on
were consumed
t enviro
nmen
orthenot. Virtualization MLaare your
othe
you prov
erst of L
b></
in bad Mana based muchallows physical piece of hardware to
ide be HTM
approac ed with the cial, but, implem anding
Creat targe es to actually r web
rily nden
cy rties are nt
of the a solid L has
into differe coding.resources
necessa pared to
chang
efi Depe prope itting utilized by multiple operating
function systems.simplerThis allows foundati job adm been arou
associat to be ben
er
Ge t
te builds commo
are not Fortuna
late Verifi e comm than on
n com Cloud computing asRun it’sremo
known etoday has changed this.
befor alitytohas irably, nd for
They they
etc.
Temp Build (e.g. bandwidth, n memory, CPU) be allocated exclusively to tely exp that som
lts whe
ually,
appear effects. Privat y, contin Every elem mov used
to be, HTML
ecte job e time
ed resu The various resourcesPerfo rm a
consumed by webperio applications
dicall (e.g. nt team
pag
individual operating entsinstances. ed to CSS
system Brow d. Earl
y HTM has expand . Whi
gration
opme because
adverse unintend d Builds sitory Build r to devel common e (HTML . ser ed far le it has don
ous Inte web dev manufacture L had very
Stage Repo
e bandwidth, memory, CPU) areIntegtallied
ration on a per-unit CI serve basis or XHT
produc tinu e Build rm an from
extensio .) All are limited more than e its
e.com
ard ML shar
tern.
ack elopers rs add
Con Refc Privat
(starting from zero) by Perfo all majorated cloud
feedb computing platforms. As a user of Amazon’s esse
term e, this
on
n. HTM EC2 cloud
ntiallycomputing es certplatform, you are result
is a lack came up ed many com
layout anybody
the pat
occur
gration as based
of the ” cycl such Build Send
autom as they builds pr L plain ain elem supp
ous Inte tional use and test concepts
soon with clev ort.
Integ
ration ors as ion with text ents in of stan peting
entat
tinu dar er wor standar
ven “build include
docum
Con kar
the con s to the
oper
to rate devel
While efer of CI Gene
notion
DZone, Inc.
Cloud Computing
the
s on
expand
ISBN-13: 978-1-934238-71-4
140 Preston Executive Dr. ISBN-10: 1-934238-71-6
Suite 100
50795
Cary, NC 27513