Tải bản đầy đủ (.pdf) (496 trang)

swt and jface in action, 2005

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (5.24 MB, 496 trang )

Matthew Scarpino
Stephen Holder
Stanford Ng
Laurent Mihalkovic
MANNING
SWT
/
JF
ace
INACTION
How to design graphical applications with Eclipse 3.0


SWT/JFace
in Action
MATTHEW SCARPINO
STEPHEN HOLDER
STANFORD NG
AND LAURENT MIHALKOVIC
MANNING
Greenwich
(74° w. long.)
Licensed to jromero <>
For online information and ordering of this and other Manning books, please go to
www.manning.com. The publisher offers discounts on this book when ordered in quantity.
For more information, please contact:
Special Sales Department
Manning Publications Co.
209 Bruce Park Avenue Fax: (203) 661-9018
Greenwich, CT 06830 email:


©2005 by Manning Publications Co. 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.
Many of the designations used by manufacturers and sellers to distinguish their products
are claimed as trademarks. Where those designations appear in the book, and Manning
Publications was aware of a trademark claim, the designations have been printed in initial
caps or all caps.
Recognizing the importance of preserving what has been written, it is Manning’s policy to have
the books they publish printed on acid-free paper, and we exert our best efforts to that end.
Manning Publications Co. Copyeditor: Tiffany Taylor
209 Bruce Park Avenue Typesetter: Tony Roberts
Greenwich, CT 06830 Cover designer: Leslie Haimes
ISBN 1-932394-27-3
Printed in the United States of America
12345678910–VHG–08 070605 04
Licensed to jromero <>
v
brief contents
1

Overview of SWT and JFace 1
2

Getting started with SWT and JFace 13
3

Widgets: part 1 27
4


Working with events 48
5

More widgets 78
6

Layouts 109
7

Graphics 133
8

Working with trees and lists 167
9

Tables and menus 190
10

Dialogs 212
11

Wizards 234
12

Advanced features 253
13

Looking beyond SWT/JFace: the Rich Client Platform 284
Licensed to jromero <>
Licensed to jromero <>

vii
contents
preface xv
acknowledgments xvi
about this book xviii
about the authors xxiii
about the title xxiv
about the cover illustration xxv
1
Overview of SWT and JFace 1
1.1 What is SWT/JFace? 2
Building GUIs with SWT 3
Simplifying
GUI development with JFace 3
1.2 Looking under the hood 4
The old standby: Swing 4

The newcomer: SWT/JFace 6
The
SWT/Swing debate 9
1.3 SWT/JFace: licensing and platform support 9
The Common Public License 9

Platforms supported 9
1.4 The WidgetWindow 11
1.5 Summary 12
Licensed to jromero <>
viii CONTENTS
2
Getting started with SWT and JFace 13

2.1 Programming in SWT 14
The HelloSWT program 14

The Display class 16
The Shell class 18
2.2 Programming in SWT/JFace 20
Model-based adapters 20

The HelloSWT_JFace program 21
Coding in JFace and
SWT/JFace 23
The ApplicationWindow class 23
2.3 Beginning the WidgetWindow application 24
2.4 Summary 26
3
Widgets: part 1 27
3.1 Introducing the Widget and Control classes 28
Understanding the Widget class 28
Working with Control objects 30
3.2 Labels 32
Styles and separators 33

Label methods 33
3.3 Involving the user with buttons 34
Causing action with push buttons and SWT.PUSH 34
Moving on with arrow buttons and
SWT.ARROW 35
Changing state with toggle buttons and
SWT.TOGGLE 35


Choosing with check buttons
and
SWT.CHECK 36

Making a single choice with
radio buttons and
SWT.RADIO 36
3.4 Containing components with Composites 38
Understanding the Composite class 39

Groups 40
SashForms 43

TabFolders 44
3.5 Updating WidgetWindow 45
Creating the Ch3_Composite class 45
Creating the WidgetWindow TabFolder 46
3.6 Summary 47
Licensed to jromero <>
CONTENTS ix
4
Working with events 48
4.1 Event processing in SWT 49
Using typed listeners and events 50

Adapters 54
Keyboard events 55

Customizing event processing with untyped
events 58


An SWT listener/event application 60
4.2 Event processing in JFace 62
Understanding actions and contributions 63

Creating Action
classes 65

Implementing contributions in an
ApplicationWindow 66

Interfacing with contributions 69
Exploring the Action class 70
4.3 Updating the WidgetWindow 74
Building the chapter 4 Composite 74
Adding Ch4_Composite to the WidgetWindow 75
4.4 Summary 77
5
More widgets 78
5.1 Editing text with SWT 79
The basic Text widget 79

The StyledText widget 82
5.2 JFace text support 88
Obtaining the JFace text packages 88

TextViewer and
Document 89

A JFace example 91

5.3 The Combo widget 100
5.4 ToolBarManager 101
ControlContribution 102

Creating toolbars by hand 103
5.5 CoolBar 103
5.6 Slider 105
5.7 ProgressBar 106
5.8 ProgressIndicator 107
5.9 Summary 108
Licensed to jromero <>
x CONTENTS
6
Layouts 109
6.1 The fill layout 110
6.2 The row layout 112
Customizing individual layout cells 114
6.3 The grid layout 116
GridData 117
6.4 The form layout 119
Using FormData 120

Specifying relations using
FormAttachment 120

Laying out controls using a form layout 122
6.5 Custom layouts 124
Calculating the layout’s size 125

Laying out the widgets 126

Updating WidgetWindow 128
6.6 Summary 132
7
Graphics 133
7.1 The graphic context 134
Creating a GC object 134

Drawing shapes on a Canvas 136
Painting and PaintEvents 138
Clipping and Canvas styles 139
7.2 Programming with colors 140
Color development with SWT 140
Additional color capability with JFace 144
7.3 Displaying text with fonts 145
Using fonts with SWT 145

Coding with fonts 148
Improved font management with JFace 150
7.4 Incorporating images in graphics 152
Allocating images 152

Coding graphics with images 154
Creating a bitmap with ImageData 155

Manipulating images
with ImageData 159

Managing images with JFace 163
7.5 Updating the WidgetWindow 164
Building the chapter 7 composite 164

Adding Ch7_Composite to the WidgetWindow 165
7.6 Summary 166
Licensed to jromero <>
CONTENTS xi
8
Working with trees and lists 167
8.1 Viewers and the Viewer framework 168
Providers 170

Listeners 172

Filters and sorters 173
8.2 Trees 176
SWT trees 176

JFace TreeViewers 177
8.3 Using the List widget 180
SWT lists 180

JFace ListViewers 181
8.4 Updating WidgetWindow 182
8.5 Summary 189
9
Tables and menus 190
9.1 Tables 191
Understanding SWT tables 191

JFace TableViewers 194
9.2 Creating menus 200
Accelerator keys 201


Creating menus in SWT 201
Using JFace actions to add to menus 204
9.3 Updating WidgetWindow 205
9.4 Summary 211
10
Dialogs 212
10.1 SWT dialogs 213
ColorDialog 213

DirectoryDialog 214

FileDialog 215
FontDialog 216

MessageBox 216
10.2 JFace dialogs 218
Message dialogs 219

Error dialogs 220

Input
dialogs 222

Progress monitor dialogs 224
Custom dialogs 228
10.3 Updating WidgetWindow 230
10.4 Summary 233
11
Wizards 234

11.1 Multipage dialogs 236
IDialogPage 236

IWizardPage 237

WizardPage 237
Licensed to jromero <>
xii CONTENTS
11.2 The wizard 239
IWizard 239

Wizard 240
11.3 Putting it all together 241
Wizard containers 241

WizardDialog 242
11.4 Combining wizards 243
WizardSelectionPage 243

IWizardNode 244
11.5 Persistent wizard data 244
DialogSettings 245
11.6 Updating WidgetWindow 246
11.7 Summary 252
12
Advanced features 253
12.1 Transferring data 254
The Transfer class 255

Drag-and-drop capability 256

Using the clipboard 261

The filesystem browser 262
12.2 Preferences 268
Preference pages 268

Field editors 270

Preference page
containers 273

Persistent preferences 274
12.3 Label decorators 276
ILabelDecorator 276

DecoratingLabelProvider 277
An example 277
12.4 The Browser widget 280
12.5 Summary 283
13
Looking beyond SWT/JFace: the Rich Client Platform 284
13.1 Understanding RCP workbenches 285
Entering data with editors 285

Displaying information with
views 287

Combining editors and views with perspectives 288
13.2 RCP: Looking under the hood 288
Creating and configuring an RCP project 288


Building the
application class 290

Adding a WorkbenchAdvisor 291
13.3 Adding views and perspectives 294
Building views 294

Arranging workbench windows with a
perspective 295

Executing an RCP application 296
Reviewing the
RCP process 297
Licensed to jromero <>
CONTENTS xiii
13.4 Populating forms with Eclipse Forms widgets 299
Using FormToolkit and the Eclipse Forms containers 299
Firing text-based events with Hyperlinks 302
13.5 Building a standalone RCP application 306
Exporting RCPExample to an application directory 306
Adding plug-ins to the application directory 307
Executing the application 308
13.6 Summary 308
appendix A Creating projects with SWT/JFace 311
appendix B

OLE and ActiveX in SWT/JFace 324
appendix C Changeable
GUIs with Draw2D 362

appendix D The Graphical Editing Framework (
GEF) 388
index 461
Licensed to jromero <>
Licensed to jromero <>
xv
preface
We developed this book with one primary goal in mind: to introduce the SWT and
JFace toolsets as simply and as thoroughly as possible. Although the available doc-
umentation covers many aspects of the two libraries, we were disappointed by the
amount (particularly in graphics) that has gone undocumented. So, we came
together in late 2003 to create an approachable book that covers both the high-level
theory and the low-level details of the combined
SWT/JFace development tools.
Thanks to the hard work of the folks at eclipse.org, SWT and JFace have
recently received quite a bit of attention and debate within the Java community.
Most of this discussion has focused on the relative merits of Swing as a standard
component of the Java 2 platform, versus
SWT as a nonstandard library that uses
native code—an approach foreign to the “write once run anywhere” mantra
embraced by most Java developers. Although Swing has many strengths, we
believe that
SWT and JFace together provide a compelling alternative for develop-
ing the user interface of many types of applications.
We wrote this book not only for Swing developers but also for new Java users
who want to build applications that reach beyond the command line. Toward this
end, we present code samples and also do our best to explain the general theories
behind graphical user interface construction. In particular, we’ve gone into great
depth concerning the Model-View-Controller paradigm, which greatly improves
both the reliability and maintainability of graphical applications.

Our goal is to share our SWT experience with you, help you decide if
SWT and
JFace make sense for your project, and help you to make effective use of these
technologies.
Licensed to jromero <>
xvi
acknowledgments
The authors would like to acknowledge and thank the people who made this book
a reality:
First, we'd like to express our appreciation to Marjan Bace, publisher of Man-
ning, for this opportunity, and to his staff, Clay Andres, Susan Capparelle, and
Dave Roberson, for their support throughout the process. Our heartfelt thanks go
to Jacquelyn Carter, our beleaguered and ever-patient developmental editor who
put up with all our whining and last-minute changes. We particularly want to rec-
ognize the hard work put in by the production team: Mary Piergies, Tiffany Tay-
lor, and Tony Roberts. Their efforts have provided the professionalism and polish
that has kept this book to its high production standard.
Next, we want to extend our sincere appreciation to our diligent reviewers: Phil
Hanna, Christophe Avare, Frank Jania, Ted Neward, Dan Dobrin, Ryan Lowe,
Steve Gutz, Carl Hume, Ed Burnette, Charles Bundy, and Robert McGovern. Their
feedback and encouragement helped us tremendously and in many cases guided
the direction of the book’s content. We’re particularly grateful for the technical
reviewing of Phil Hanna. There’s nothing worse than a programming book with
poor code, and his exacting tests ensured that our code will work as promised.
We also want to thank the Eclipse.org community in general. Not only have
they produced a quality product, but this book wouldn’t be possible without their
dedication to technical support. Their programmers have promptly and thor-
oughly answered our many questions, and their documentation has provided a
great deal of assistance. Of course, we’re also indebted to the Eclipse developers
Licensed to jromero <>

ACKNOWLEDGMENTS xvii
for making their code open source, thereby giving us the means to look under the
hood and discover exactly how the
SWT/JFace mechanisms function.
Finally, we’d like to thank you for purchasing our book. We hope you enjoy it
as much as we’ve enjoyed creating it, and we wish you the best of luck coding with
SWT/JFace!
Licensed to jromero <>
xviii
about this book
This book is written with the intermediate to advanced Java programmer in mind.
We assume that you’re familiar with the basics of Java syntax and comfortable con-
sidering design alternatives where there may not be a single choice that is supe-
rior in all situations.
Having some experience with developing graphical applications, whether in
Java or any other language, will be helpful but isn’t necessary. We define all terms
as they’re introduced and attempt to point out the purpose behind each widget as
well as discuss the technical details of how to use it. However, this isn’t a book
about user interface design, so we won’t attempt to cover the myriad details that
go into assembling a compelling user experience out of the widgets we present.
We assume that most readers have some experience with Swing, but such expe-
rience isn’t necessary to fully enjoy this book. We attempt to draw comparisons to
Swing where we feel that doing so imparts additional understanding for Swing vet-
erans, but these comparisons are secondary to the main discussion of each topic.
We have made sure you can understand every topic in this book without having
programmed a single line of Swing code.
Roadmap
This book is structured around the development of a sample application—the
Widget Window—that shows off the details of each component included in
SWT

and JFace. The application consists of a series of tabs, one for each chapter. At the
end of each chapter, we present code that you can drop into the overall project to
Licensed to jromero <>
ABOUT THIS BOOK xix
add another tab. Where the initial chapters develop the foundation of the appli-
cation, the code for the later chapters can stand on its own without needing that
from the preceding chapters. We hope this approach lets you focus on the topics
that are of particular interest to you, using the framework of the Widget Window
application to play with the code and see the effects of different parameters on
each component.
Beyond a general introduction to the tools, we cover several specific aspects of
SWT/JFace:

The relationship between SWT and JFace—When you first approach these two
libraries, it’s difficult to know when to use one over the other, or why JFace
exists. We explain the seeming redundancies between the two libraries and
demonstrate the trade-offs in coding with one or the other.

Rules of thumb concerning GUI development—Having used these tools exten-
sively, we’ve found a number of routines that simplify the process of creat-
ing
GUIs. We’ve also encountered a number of places where SWT/JFace’s
operation differs from its documentation. In each case, we provide explana-
tions and practical examples to help you avoid these pitfalls and create reli-
able SWT/JFace applications.

Cross-platform development—Between SWT and JFace, you can find many dif-
ferent ways to build the same user interface. However, some methods trans-
late well across operating systems, and some don’t. Throughout this book,
we present screenshots on multiple windowing platforms to show you how

your application will appear.

Practical code examples—When we came up with the example code in this
book, we held two priorities in mind: We kept them concise, for hands-on
readers; and we made them modular, so you can use them in SWT/JFace
applications you build in the future.

Toolsets that build on SWT/JFace—We’re excited to present the first thorough
walkthrough of the Draw2D and Graphical Editor Framework (
GEF)
toolsets. These libraries, which build on the capabilities of
SWT and JFace,
greatly extend the power and flexibility of
GUI design.
Chapter 1, “Overview,” presents the history of
SWT and JFace and places these tech-
nologies in context. We present an overview of the history of graphical user inter-
face development using Java and discuss the organization of the various classes
and packages within
SWT and JFace.
Chapter 2, “Getting started with SWT/JFace,” shows you how to set up a project to
use
SWT and JFace, either within the Eclipse IDE or as a standalone project built
Licensed to jromero <>
xx ABOUT THIS BOOK
from the command line. After showing how to implement a traditional “Hello
World” application using
SWT and JFace, we introduce the basic framework on
which the Widget Window will be built.
Chapter 3, “Widgets: part 1,” discusses the inheritance hierarchy used by the SWT

and JFace classes. We also discuss several concepts common to all widgets within
SWT and show how to use some basic, common widgets such as buttons and labels.
Chapter 4, “Working with events,” explains how to enable your application to
react appropriately when the user takes an action such as clicking a button on the
screen. We show the details of low-level event classes in both
SWT and JFace and
discuss the higher-level Action framework that makes handling events easier.
Chapter 5, “More widgets,” dives back in to the discussion of individual compo-
nents provided by
SWT. Most important, we discuss how to let users edit text
within your application, and we cover a variety of useful widgets that are often
used in user interfaces.
Chapter 6, “Layouts,” takes a break from the details of individual widgets to dis-
cuss ways to organize widgets on the screen. After covering the built-in layout
managers provided by
SWT, we show how to create a custom layout manager if the
default ones don’t meet the needs of your application.
Chapter 7, “Graphics,” covers low-level SWT facilities for drawing graphics by
hand. In addition, we show how to programmatically manipulate colors, fonts,
and images from within
SWT.
Chapter 8, “Working with trees and lists,” introduces the Viewer framework, a set
of classes and interfaces provided by JFace to make working with data easier. We
use this discussion of viewers and their related classes to show you how to easily
work with tree and list widgets.
Chapter 9, “Tables and menus,” continues the Viewer framework discussion from
chapter 8 and includes several advanced features of the framework. We show how
these features enable you to create tables that users can easily and intuitively edit.
The chapter ends with a discussion of menus and how they tie into the action
classes from chapter 4.

Chapter 10, “Dialogs,” covers ways to create dialog boxes in both
SWT and JFace.
We discuss the dialog boxes provided by
SWT and JFace and show how to create
your own dialogs when necessary.
Chapter 11, “Wizards,” shows how to use the framework provided by JFace to
create a wizard that guides the user through a series of steps.
Chapter 12, “Advanced features,” covers a variety of miscellaneous features. These
are important topics to understand in order to fully master
SWT and JFace, but
they aren’t essential to get a basic application running. We discuss subjects such as
Licensed to jromero <>
ABOUT THIS BOOK xxi
implementing drag and drop, interacting with the operating system’s clipboard,
and embedding a web browser in your application.
Chapter 13, “Looking beyond
SWT/JFace: the Rich Client Platform,” shows how to
build custom workbench applications that contain editors and views. In addi-
tion, this chapter presents the new Eclipse Forms toolset for designing form-like
applications.
Appendix A, “Creating projects with SWT/JFace,” shows how set up a Java project
that uses
SWT and JFace. Specifically, it covers how to find the necessary libraries
and set up common IDEs such as Eclipse.
Appendix B, “OLE and ActiveX in SWT/JFace,” covers facilities provided by SWT for
integrating with the Windows operating system. Obviously, the techniques we dis-
cuss in this appendix are relevant only to developers willing to tie themselves closely
to one operating system; as such, they may not be of interest to some readers.
Appendix C, “Changeable GUIs with Draw2D,” shows a framework you can use to
create custom widgets for use in

SWT. We cover the creation of a custom widget
used in appendix D.
Appendix D, “The Graphical Editing Framework (GEF),” covers the most complicated
topic in this book and requires knowledge of almost every aspect of JFace as well as
the Eclipse Workbench.
GEF is a powerful framework that you can use to create to
create powerful graphical editors for your applications. This appendix uses the cus-
tom widget developed in appendix C to create a flowchart editor application.
If you have any questions or concerns about our content, visit the www.man-
ning.com/scarpino web site. From there, we can answer questions and provide
further explanations. We also provide our example code for download.
Conventions
Throughout this book, the text follows certain conventions. Method and variable
names appear in
monotype font in the text. Code snippets that illustrate a tech-
nique in context without necessarily covering every detail required to get the
code to compile are also presented in
monotype font, as are full code listings. Any
code listing (preceded by a “Listing
X.Y” header) can be typed in, compiled, and
run as is.
We also present several
UML diagrams in this book. These diagrams are in the
spirit of what Martin Fowler refers to as “
UML as sketch”—they aren’t full-blown,
comprehensive diagrams that cover every member variable and private method of
the classes in question. Rather, they’re intended to convey essential information
about the relationship between certain classes and interfaces at a high level. The
text and code samples around each diagram discuss the low-level details necessary
to make effective use of the classes presented in the diagrams.

Licensed to jromero <>
xxii ABOUT THIS BOOK
Source code downloads
Source code for the programming examples in this book is available for download
from the publisher's web site at www.manning.com/scarpino.
Author Online
Purchase of SWT/JFace in Action includes free access to a private web forum run by
Manning Publications where you can make comments about the book, ask techni-
cal questions, and receive help from the authors and from other users. To access
the forum and subscribe to it, point your web browser to www.manning.com/scar-
pino. This page provides information on how to get on the forum once you are
registered, what kind of help is available, and the rules of conduct on the forum.
Manning's commitment to our readers is to provide a venue where a meaning-
ful dialog between individual readers and between readers and the authors can
take place. It is not a commitment to any specific amount of participation on the
part of the authors, whose contribution to the AO remains voluntary (and
unpaid). We suggest you try asking the authors some challenging questions lest
their interest stray!
The Author Online forum and the archives of previous discussions will be
accessible from the publisher's web site as long as the book is in print.
Licensed to jromero <>
xxiii
about the authors
MATT SCARPINO has more than 10 years of software design and engineering experi-
ence. He uses Eclipse to build editing software for reconfigurable computing and
has submitted code for Eclipse’s graphical library. He lives in Fort Worth, Texas.
S
TEPHEN HOLDER is a software engineer who has worked as a consultant for several
large commercial and government agencies on enterprise-level Java projects,
including writing Eclipse plug-ins to streamline the development process. He cur-

rently resides in Tustin, California.
S
TANFORD NG is the cofounder of Nuglu, LLC and is currently working on improv-
ing back-end systems at Automotive.com, a top-5 automotive e-commerce site. He
is also a co-conspirator with Dr. Robert Nideffer behind the International award-
winning Proxy/
MAM research project. He lives in Irvine, California.
L
AURENT MIHALKOVIC is a technology consultant with 10 years’ experience design-
ing solutions in C/C
++
/Java/COM. He currently lives between Vancouver and
Toronto, Canada.
Licensed to jromero <>
xxiv
about the title
By combining introductions, overviews, and how-to examples, the In Action books
are designed to help learning and remembering. According to research in cogni-
tive science, the things people remember are things they discover during self-
motivated exploration.
Although no one at Manning is a cognitive scientist, we are convinced that for
learning to become permanent it must pass through stages of exploration, play,
and, interestingly, retelling of what is being learned. People understand and
remember new things, which is to say they master them, only after actively explor-
ing them. Humans learn in action. An essential part of an In Action guide is that it
is example-driven. It encourages the reader to try things out, to play with new
code, and to explore new ideas.
There is another, more mundane, reason for the title of this book: our readers
are busy. They use books to do a job or to solve a problem. They need books that
allow them to jump in and jump out easily and learn just what they want just when

they want it. They need books that aid them in action. The books in this series are
designed for such readers.
Licensed to jromero <>

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×