Java Guide V
Java Guide V
Java Guide V
CONTENTS INCLUDE:
n n
About Java GUI Development The Anatomy of a Swing Application Swing Components The Anatomy of an SWT Application SWT Components Event Handling and more...
By James Sugrue
www.dzone.com
CORE PACKAGES
Package
javax.swing javax.swing.border
Purpose
Provides a set of lightweight (all-Java language) components that, to the maximum degree possible, work the same on all platforms. Provides classes and interface for drawing specialized borders around a Swing component. Contains classes and interfaces used by the JColorChooser component. Provides for events red by Swing components. Contains classes and interfaces used by the JFileChooser component. Provides user interface objects built according to the Basic look and feel. Provides user interface objects built according to the Java look and feel (once codenamed Metal), which is the default look and feel. Provides user interface objects that combine two or more look and feels. Synth is a skinnable look and feel in which all painting is delegated. Provides classes and interfaces for dealing with javax.swing.JTable. Provides classes and interfaces that deal with editable and noneditable text components. Provides the class HTMLEditorKit and supporting classes for creating HTML text editors. Provides the default HTML parser, along with support classes. Provides a class (RTFEditorKit) for creating Rich-Text-Format text editors. Provides classes and interfaces for dealing with javax.swing.JTree. Allows developers to provide support for undo/redo in applications such as text editors.
javax.swing.colorchooser javax.swing.event javax.swing.lechooser javax.swing.plaf.basic javax.swing.plaf.metal javax.swing.plaf.multi javax.swing.plaf.synth javax.swing.table javax.swing.text javax.swing.text.html javax.swing.text.html.parser javax.swing.text.rtf javax.swing.tree javax.swing.undo
Hot Tip
Swing relies a lot on the MVC structure, where a component consists of a data model, a visual representation and a controller for event handling.
DZone, Inc.
www.dzone.com
javax.swing.JList
javax.swing.JMenu
javax.swing.JApplet
JApplet allows the addition of menus and toolbars to applets hosted in a browser. Since Java 6 Update 10, applets can also be dragged outside of the browser to run on the desktop. Construction code for applets go into the init() method, rather than the applets constructor.
public class SwingApplet extends JApplet { public SwingApplet() {} public void init() { setSize(100, 100); } }
javax.swing.JTabbedPane
javax.swing.JPasswordField javax.swing.JColorChooser
javax.swing.JEditorPane
javax.swing.JTextPane
Purpose
Creates a custom dialog, either modal or modeless. JOptionPane can be used to create standard dialogs. JPanel is a generic lightweight container used to group components together and add to other windows such as JFrames. Provides a scrollable view of another lightweight component. The JScrollPane provides a viewport with optional scrollbars at veritical and horizontal positions. Displays two components either side by side (JSplitPane. HORIZONTAL_SPLIT), or one on top of the other (JSplitPane. VERTICAL_SPLIT). Provides many of the features of a native frame, including dragging, closing, becoming an icon, resizing, title display, and support for a menu bar, allowing Swing applications to take on a multiple document interface. Adds depth to a Swing container, allowing components to overlap each other when needed. For convenience, JLayeredPane divides the depth-range into several different layers. Layers available include DEFAULT_LAYER, PALETTE_LAYER, MODAL_LAYER, POPUP_LAYER, DRAG_LAYER.
javax.swing.JTable
javax.swing.JSplitPane
javax.swing.JTextArea
javax.swing.JInteralFrame
javax.swing.JTree
javax.swing.JLayeredFrame
DZone, Inc.
www.dzone.com
Containment
Hot Tip
Each component can only be contained once. If you add a component to another container, after adding it to a different one previously, it will be removed from the previous container, and only added to the last one.
Used to specify how to ll any unused space in the grid cell. Options are NONE (default), HORIZONTAL, VERTICAL or BOTH. Species how many pixels to pad around the components minimum size in the x or y direction. Species how much should be added to the external padding of the component out to the edges of its display area. Species where the component should be positioned in its display area. Determines how to distribute space around a component, for resizing behaviour.
weightx, weighty
EVENT HANDLING
Standard click events on Swing components are handled using the java.awt.event.ActionListener interface. Implemented action handlers need to implement the public voidactionPerformed(ActionEvent e), provided the component has registered the action listener using the addActionListener() method. Three interfaces are provided to handle mouse events on components:
Interface java.awt.event.MouseListener Methods
public void mouseClicked(MouseEvent e); public void mousePressed(MouseEvent e); public void mouseReleased(MouseEvent e); public void mouseEntered(MouseEvent e); public void mouseExited(MouseEvent e); public void mouseWheelMoved(MouseWheelEvent e); public void mouseDragged(MouseEvent e) public void mouseMoved(MouseEvent e);
java.awt.FlowLayout
A ow layout arranges components in a directional ow one after the other, moving onto a new line when no more components t on the current line. Direction is determined by the containers componentOrientation property and may be one of two values: ComponentOrientation.LEFT_TO_RIGHT or
ComponentOrientation.RIGHT_TO_LEFT
java.awt.event.MouseWheelListener java.awt.event.MouseMotionListener
Flow layout is the default layout manager for AWT and Swing components.
java.awt.GridLayout
GridLayout lays out a containers components in a rectangular grid. The container is divided into equal-sized rectangles, and one component is placed in each rectangle. Typically, a GridLayout is constructed by specifying the number of rows and columns.
Alternatively, you can extend the java.awt.event.MouseAdapter class, which packages all three interfaces into a single abstract class to make it easier to handle particular mouse events.
java.awt.BorderLayout
BorderLayout lays out the components in ve regions: NORTH, SOUTH, EAST, WEST and CENTER. As each component is added to a container with a border layout, the location is specied similar to: container.add(component, BorderLayout.CENTER);
java.awt.CardLayout
CardLayout acts as an organisation of stacked components on a container, with only one card being visible at a time. The rst component added is the visible component when the container is rst displayed. Methods exist to go through the stack sequentially or to access a particular card.
javax.swing.BoxLayout
BoxLayout allows multiple components to be laid out vertically (Y_AXIS) or horizontally (X_AXIS). Components do not wrap, so when the frame is resized the components remain in their initial arrangement. Components are arranged in the order that they are added to the layout manager.
long running task run in a background thread and provide updates to the UI either when done, or while processing. Subclasses of SwingWorker must implement the doInBackground() method to perform background computation.
java.awt.GridBagLayout GridBagLayout is the most exible layout manager, maintaining a dynamic, rectangular grid of cells. Each component can occupy one or more cells, and has an instance of GridBagConstraints to specify how a component should be displayed in its display area. The following table illustrates the options in GridBagConstraints:
Variable Name
gridx, gridy gridwidth, gridheight
CORE PACKAGES
package
org.eclipse.swt
Use
Species the location on the grid to place the component, with gridx=0, gridy=0 as the top left hand corner. Species the number of rows, or columns that will be used for a components display area. The default value is 1.
Purpose
Provides the class SWT which contains all of the constants used by SWT as well as a small selection of error handling routines and queries such as getPlatform and getVersion. Contains the classes that support platform accessibility.
org.eclipse.swt.accessibility
DZone, Inc.
www.dzone.com
org.eclipse.swt.awt
Contains the SWT_AWT bridge, allowing AWT components to be embedded in SWT components and vice versa. Provides the classes to implement the browser user interface metaphor. Contains the custom widgets which were written to provide the standard look and feel of the Eclipse platform. Contains the classes which make up the public API of the SWT Drag and Drop support.
controls, similar to a JPanel in Swing. Composite is the super class of all composites, and can also be used directly.
org.eclipse.swt.widgets.Dialog
SWT also provides a Dialog class, which should be modal with a Shell as its parent.
org.eclipse.swt.widgets.Button
org.eclipse.swt.widgets.Combo
In order to create a shell, you need to run the event dispatch loop continuously until an exit condition occurs, i.e. the shell is closed. Following this event the display must be disposed.
public static void main (String [] args) { Display display = new Display (); Shell shell = new Shell (display); //create SWT widgets on the shell shell.open (); while (!shell.isDisposed ()) { if (!display.readAndDispatch ()) display.sleep (); } display.dispose (); }
org.eclipse.swt.widgets.ColorDialog
org.eclipse.swt.widgets.CoolBar
org.eclipse.swt.custom.CTabFolder
The Display provides a connection between SWT and the platforms GUI system. Displays are used to manage the event dispatch loop and also control communication between the UI thread and other threads. The Shell is a window managed by the OS platform window manager. Top level shells are those that are created as a child of the display. These windows are the windows that users move, resize, minimize, and maximize while using the application. Secondary shells also exist, such as dialogs these are created as the child of other shells. Any widget that is not a top level shell must have a parent shell or composite. Composite widgets are widgets that can have children. In SWT the Shell is the root of a widget hierarchy.
org.eclipse.swt.widgets.DateTime
org.eclipse.swt.widgets.ExpandBar
org.eclipse.swt.widgets.Group
Hot Tip
Native platforms require explicit allocation and freeing of OS resources. In keeping with the SWT design philosophy of reecting the platform application structure in the widget toolkit, SWT requires that you explicitly free any OS resources that you have allocated, the Widget.dispose() method is used to free resources.
org.eclipse.swt.widgets.Label
org.eclipse.swt.widgets.Link
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
DZone, Inc.
|
www.dzone.com
org.eclipse.swt.widgets.Menu
in a composite using this layout can have an associated GridData object which congures the control. A control can use a GridData object through its setLayoutData method. Note: GridData objects should not be reused between widgets, as it must be unique for each widget. A grid can have a number of columns associated with it. As widgets are added they are laid out in the columns from left to right. A new row is created when the previous row has been lled. The following table illustrates the options in GridData:
Variable Name Use
Species the location on the grid to place the component, with gridx=0, gridy=0 as the top left hand corner. Species whether the width or height of the widget will change depending on the size of the parent composite. The number of pixels to move in from the left or the top of the cell. The number of rows or columns that the widget will occupy. The preferred height or width of this widget. The minimum height or width of the widget. Informs the layout manager to ignore this widget when sizing and positioning controls
org.eclipse.swt.widgets.ProgressBar
org.eclipse.swt.widgets.Slider
org.eclipse.swt.widgets.Scale
org.eclipse.swt.widgets.Spinner
org.eclipse.swt.custom.StyledText
org.eclipse.swt.widgets.TabFolder
org.eclipse.swt.layout.FormLayout
org.eclipse.swt.widgets.Table
org.eclipse.swt.widgets.Text
FormLayout positions children of a composite control by using FormAttachments to optionally congure 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 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 elds of the childs FormData. If a side is not given an attachment, it is dened as not being attached to 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 top or bottom, it is automatically attached to the left and top of the composite respectively.
org.eclipse.swt.widgets.ToolBar
org.eclipse.swt.widgets.Tray
org.eclipse.swt.widgets.Tree
EVENT HANDLING
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.
Un-typed Listeners
Creating un-typed listeners in SWT involves three classes from the org.eclipse.swt.widgets package:
Event Listener Widget This class provides a description of the event that has been triggered, including elds for type, widget and time The listener interface needs to be implemented by any class that listens for events. The interface simply denes a handleEvent(Event e) method in order to do this. Each widget object has an addListener(int eventType, Listener handler) method with a corresponding removeListener method.
org.eclipse.swt.layout.FillLayout
FillLayout lays all widgets in a single continuous row or column. All widgets are forced to be the same size in this layout. Unlike Swings FlowLayout, FillLayout does not wrap, but you can specify margins and spacing. FillLayout is useful when a Composite only has one child, as it can cause the child of the composite to ll the shell.
FillLayout fillLayout = new FillLayout(SWT.VERTICAL); shell.setLayout(fillLayout);
The addListener method accepts an eventType method. The following table lists out the possible values for this eld:
Event Type
SWT.Activate, SWT.Deactivate SWT.Arm SWT.Close SWT.DefaultSelection SWT.Dispose SWT.DragDetect SWT.EraseItem SWT.Expand, SWT.Collapse
Description
Control is activated or deactivated. The mouse pointer hovers the MenuItem A Shell is about to close The user selects an item by invoking a default selection action. A widget is about to be disposed. The user has initiated a possible drag operation. A TableItem or TreeItem is about to have its background drawn. An item in a Tree is expanded or collapsed.
org.eclipse.swt.layout.RowLayout
RowLayout places components in horizontal rows or vertical columns within the parent Composite. Unlike FillLayout, RowLayout allows components to wrap and also provides margins and spacing. Rather than all components being the same size, each control can have its own parameters using the RowData object. A control can use this object through its setLayoutData method.
org.eclipse.swt.layout.GridLayout
The most exible layout manager in SWT is GridLayout, which lays components out in a grid formation. Each control that is placed
DZone, Inc.
|
www.dzone.com
SWT.Help SWT.Iconify, SWT.Deiconify SWT.ImeComposition SWT.MeasureItem SWT.MenuDetect SWT.Modify SWT.Move, SWT.Resize SWT.Movement SWT.PaintItem SWT.Selection SWT.SetData SWT.Settings SWT.Show, SWT.Hide SWT.Traverse SWT.Verify SWT.FocusIn, SWT.FocusOut SWT.KeyDown, SWT.KeyUp SWT.MouseDown, SWT.MouseUp, SWT.MouseDoubleClick SWT.MouseMove SWT.MouseEnter, SWT.MouseExit, SWT.MouseHover SWT.MouseWheel SWT.Paint
The user has requested help for a widget. A Shell has been minimized, maximized, or restored. Allows custom text editors to implement in-line editing of international text. The size of a custom drawn TableItem or TreeItem is being requested. The user has requested a context menu. The widgets text has been modied. A control has changed position or has been resized, either programmatically or by user. An updated caret offset is needed in response to a user action in a StyledText. A TableItem or TreeItem is about to have its foreground drawn. The user selects an item in the control. Data needs to be set on a TableItem when using a virtual table. An operating system property, such as a system font or color, has been changed. A controls visibility has changed. The user is trying to traverse out of the control using a keystroke. A widgets text is about to be modied. A control has gained or lost focus. The user has pressed or released a keyboard key when the control has keyboard focus. The user has pressed, released, or double-clicked the mouse over the control. The user has moved the mouse above the control. The mouse has entered, exited, or hovered over the control.
THREADING IN SWT
In order to keep the UI as responsive as possible, any long running operations triggered by a UI event should be run in a separate thread. The application program runs the event loop in its main thread and dispatches events directly from this thread. The UI thread is the thread in which the Display was created. All other widgets must be created in the UI thread.
Hot Tip
SWT will trigger an SWTException for any calls made from a non-UI thread that must be made from the UI thread.
Applications that wish to call UI code from a non-UI thread must provide a Runnable that calls the UI code. The methods syncExec(Runnable) and asyncExec(Runnable) in the Display class are used to execute these runnables in the UI thread during the event loop. syncExec(Runnable) should be used when the application code in the non-UI thread depends on the return value from the UI code or otherwise needs to ensure that the runnable is run to completion before returning to the thread. SWT will block the calling thread until the runnable has been run from the applications UI thread. asyncExec(Runnable) should be used when the application needs to perform some UI operations, but is not dependent upon the operations being completed before continuing.
The mouse wheel has been rotated. Control has been damaged and requires repainting.
RECOMMENDED BOOK
Building on two internationally best-selling previous editions, Eclipse Plug-ins, Third Edition, has been fully revised to reect the powerful new capabilities of Eclipse 3.4. Leading Eclipse experts Eric Clayberg and Dan Rubel present detailed, practical coverage of every aspect of plug-in development, as well as specic, proven solutions for the challenges developers are most likely to encounter.
James Sugrue has been editor at both Javalobby and EclipseZone for over two years, and loves every minute of it. By day, James is a software architect at Pilz Ireland, developing killer desktop software using Java and Eclipse all the way. While working on desktop technologies such as Eclipse RCP and Swing, James also likes meddling with up and coming technologies such as Eclipse e4. His current obsession is developing for the iPhone and iPad, having convinced himself that its a turning point for the software industry.
BUY NOW
books.dzone.com/books/eclipseplugins
#82
Get More Refcardz! Visit refcardz.com
CONTENTS INCLUDE:
Cost by... youTechnologies Data t toTier Comply. brough Platform Management and more... borate.
Aldon
Chan ge. Colla
ref ca
Cloud Computing
active Repo are within d units This Refcard will introduce to you to cloud softw riente computing, with an loping ine task-o it e Deve Mainl es by emphasis on these so you can better understand ines providers, Comm softwar chang codel e code ding Task Level sourc es as aplatform what it is a cloud computing can offer your trol ut web line Policy nize of buil NT Orga Code e witho it chang cess ion con e name sourc T CO and subm applications. it the pro jects vers are from with uniqu ABOU softw (CI) is um the build evel Comm build a pro minim Label Task-L ies to gration ed to activit blem the bare ion ate all cies to t ous Inte committ USAGE SCENARIOS to a pro Autom congurat nden ymen Build depe al deplo t Continu ry change manu Label d tool solution fective nmen a the same stalle , ) Build eve t, use target enviro (i.e. , inef ated ce pre-in with ymen Redu problem Autom terns ns (i.e. ory. d deploEAR) in each Pay only what you consume ticular tagge via pat or cies -patter s that reposit t nden For each (e.g. WAR es lained ) and anti the par solution duce nmen al Depe ge librari x t exp Web application deployment until a few years ago was similar t enviro packa Minim are be nden text to to pro all targe rity all depe tterns can used CI can ticular con le that alizeplans with tend y Integ to most phone services: alloted resources, late Centr Binar ts with an Anti-pa they es, but etimes temp nt nmen on ng end, in a par hes som cess. geme practic t enviro e a single incurred cost whether such resources were consumed or pro enti the based thenot. Mana targe bad in Creat cy nt es to rties are rily nden implem approac ed with the cial, but, chang prope Depe into differe itting er necessa pared to e te builds e comm late Veri remo associat to be ben befor etc. are not Cloud computing asRun its known etoday has changed this. Temp n com Build ually, They Privat lts whe y, contin appear effects. rm a nt team dicall The various resources consumed by webperio applications (e.g. Perfo opme ed resu d Builds sitory Build gration r to devel Repo Stage adverse unintend ration on a per-unit bandwidth, memory, CPU) areInteg tallied basis CI serve e ous Inte from e Build rm an tinu ack ard produc Privat Con feedb computing platforms. Refc on (starting from zero) by Perfo all major cloud tern. ated occur term based autom e, this as as they the pat builds Build gration Send of the soon cycl such ration ion with ors as Integ entat ous Inte tional use and test concepts tinu docum ven oper Con build include the con s to the rate devel to Gene While of CI efer notion the s on expand
Vis it
Ge t
Mo re
ww w.dzone.com
S INUOU
INTEG
RATION
Re fca
rd z!
e.com
Ge t Mo re
E: INC LUD gration NTS ous Inte Change CO NTE Continu at Every ns About Software i-patter Build and Ant Patterns Control ment Version e... Manage s and mor Build Practice d Buil
to isolat space n e Work riptio itory a Privat Desc ge These companies have webmana applications are in long deployed trol repos to n-con lop softw ing and making them Deve a versio that adapt and scale bases, rn les toto large user ize merg Patte it all minim le space Comm ine to many to cloud computing. s multip e Work knowledgeable in a mainl aspects related Privat that utilize lop on Deve code lines a system sitory of work
rdz .co
Re fca
rdz !
However, the demands and technology used on such servers has changed substantially in recent years, especially with the entrance of service providers like Amazon, Google and es Microsoft. e chang
Elem al Elem ents ents Large scale growth scenarios involving specialized and mor equipment e... away by (e.g. load balancers and clusters) are all but abstracted
Vis it
#84
dz. com
ref car
Web applications have always been deployed on servers connected to what is now deemed the cloud.
ation one time events, cloud Having the capability to support Useful Open the gradual growth curves computing platforms also facilitate Page Source Structure Tools faced by web applications. Key
HTML
Basics
LUD E:
Valid
ML
Structur
ICS In addition, several cloud computing platforms support data HTM tier technologies that L exceed the precedent set by Relational and XHT HTML ML Database Systems (RDBMS): Map Reduce, are the web service APIs, is used prog foundati as the etc. Some platforms ram support large scale RDBMS deployments. The src grap on of hical and Java s written in attribute all and the also rece JavaScri user interfac web develop desc as the e in clien ment. ive data pt. Server-s the ima alt attribute ribes whe output likew t-side ide lang ge is describe re the ima mec CLOUD COMPUTING PLATFORMS AND ise hanism. from unavaila web ge le s alte Nested was onc use HTML The eme pages and uages like ble. rnate can be UNDERLYING CONCEPTS and XHT text that e tags use HTM PHP rging found, Tags standard a very loos ML as Ajax is disp can L tech ely-de thei ization, layed cannot be (and freq need ned lang r visual eng nologies if but as for stan overlap uen it has ine. HTM b></ Amazon EC2: Industry standard software and uag virtualization whether dards , so <a>< tly are) nest e with a> is has bec become very little L you cho platform ne. b></ ed insid moron Amazons cloud computing isome heavily based the curr a></ e imp e b> is more ent stan ose to writ orta not lega each othe app nt, that will software industry standard and virtualization e HTM technology. dard HTM r. Tags l, but s will L or XHT arent. Reg the L VS <a>< help and XHT simplify all XHTM b></ ML, und ardless you prov your MLaare of L othe erst Virtualization physical piece of hardware to be HTM muchallows ide anding actually r web a solid L has of the coding. simpler foundati utilized by multiple operating This allows resources function systems. job adm been arou Fortuna commo than on nd for ality irably, they has (e.g. bandwidth, memory, CPU) to be allocated exclusively to exp tely som that n used mov ecte elem e time Every job ed to d. Earl to be, HTML ents . Whi pag Brow individual operating system instances. CSS. y HTM has expand because ser common e (HTML ed far le it has don or XHT web dev manufacture L had very e its extensio .) All are ML shar limited more than rs add elopers esse As a user of Amazons cloud computing platform, you are result anybody layout es cert n. HTM EC2 ntially is a lack came up ed many com pr supp ain elem plain L with clev ort. of stan peting text ents in dar er wor standar kar
HTM
L BAS
50795
DZone communities deliver over 6 million pages each month to more than 3.3 million software developers, architects and decision makers. DZone offers something for everyone, including news, tutorials, cheat sheets, blogs, feature articles, source code and more. DZone is a developers dream, says PC Magazine.
9 781934 238714
Version 1.0
Copyright 2010 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher.