1 – Carousel, User Guide

CAROUSEL User Guide Version 3.0

© Xoetrope Ltd. 2005, All rights reserved.

Copyright © 2003-2005 Xoetrope Ltd. Java is a trademark of . Xoetrope reserves the right to modify Carousel in the future and while every effort has been made to ensure this document correctly depicts the software no warranty is made as to the accuracy of this document.

• • • 2 • • • Carousel, User Guide 1 – Table of Contents

Table of Contents

CAROUSEL 2 Table of Contents 3

SECTION I 17 1 About this book...... 19 User Guide Conventions...... 19 XUI and Carousel...... 20 Contacting Xoetrope developer support ...... 20 2 Introduction ...... 21 What is Carousel? ...... 21 What can be built with Carousel?...... 22 What does Carousel do? ...... 23 How does Carousel work? ...... 24 Licensing ...... 26 3 Why Carousel? ...... 27 Background...... 27 Why do we build applications at all? ...... 28 The Form Metaphor ...... 28 Beyond Forms...... 29 HTML’s limits ...... 29 Scripting ...... 30 Application delivery in a connected world...... 30 Rich Client to the Rescue ...... 31 So Why Carousel?...... 31 The Development challenge ...... 31 4 Related technologies ...... 33 Carousel versus HTML ...... 33 Carousel versus AJAX...... 33 Carousel versus Java...... 34 Carousel versus Servlet and Server Side Technologies...... 34 Carousel versus .NET ...... 35 Carousel versus XUL , XForms, XAML et al ...... 35 Carousel versus Ajax ...... 36 Other issues ...... 36 Legacy application support...... 36 Simple single language support ...... 37 Separation of roles ...... 37 Occasionally connected...... 37 Branding ...... 37 Performance and server load...... 37

• • • • 3 • • 1 – Table of Contents Carousel, User Guide

SECTION II 39 5 Installing Carousel ...... 41 Downloading Carousel...... 41 Carousel components ...... 41 XUI components...... 42 Installing NetBeans...... 43 Loading Carousel...... 44 Installing the samples ...... 46 Installing the Eclipse plug-in ...... 47 6 A quick tour of the editor ...... 49 Creating a new project...... 49 The project view...... 55 Pages and resources...... 55 The page designer ...... 57 Components...... 58 Styles...... 60 Source code...... 60 XML ...... 62 Compilation ...... 62 Testing...... 62 Deployment ...... 62 7 Running applications ...... 63 Command-line startup sequence for applications...... 63 Java Web Start Start-up Sequence ...... 64 HTML/Applet Start-up Sequence...... 64 Generic Initialization...... 65 Startup file stubs ...... 66 Eclipse Debugging...... 66 8 Getting started...... 67 Hello world ...... 67 Hello world redux ...... 68 Beyond HelloWorld ...... 69 Building a simple address form...... 70 Applying style...... 71 Validating user inputs ...... 73 Using data ...... 74 Responding to events...... 76 Changing pages ...... 77 9 Projects...... 81 A project’s role ...... 81 Creating a new project...... 82 Project setup...... 83 General setup ...... 84 Frames setup...... 85 Files Setup ...... 86 Extensions setup ...... 87 Extra setup...... 87 Services provided ...... 88

• • • 4 • • • Carousel, User Guide 1 – Table of Contents

10 Designing pages ...... 89 The role of pages ...... 89 Creating a new page ...... 89 Opening the page ...... 89 Opening the page in a frameset...... 90 Preferred page size...... 91 Adding components...... 91 Selecting and sizing a component ...... 92 Nudging a component ...... 93 Aligning components ...... 93 Setting up guides...... 93 Layout managers and constraints...... 94 Setting properties ...... 95 In-situ editing ...... 95 Quickly setting the content ...... 96 Styling a component ...... 96 Delete, Cut, Copy and Paste ...... 97 Locking components...... 97 Hidden components ...... 98 Hooking up code ...... 98 Inserting predefined code...... 99 Working with data ...... 99 Setting up a database table ...... 99 Setting up POJOs ...... 99 Setting up static data ...... 99 Binding ...... 99 Working with validations ...... 100 And now for the XML...... 100 Working with included pages ...... 101 Saving...... 101 11 Building pages with XML...... 103 Basic form building...... 103 Built-in components...... 105 Common properties ...... 107 Panels ...... 108 ScrollPanes ...... 108 Frames ...... 108 Using imported pages ...... 109 Repeat elements...... 109 Layout managers ...... 110 Validations...... 112 Events ...... 113 Data bindings...... 114 12 Building pages with Java ...... 117 Basic form building...... 117 Using stylesheets...... 118 Event handling ...... 119 Data binding...... 120 Validations...... 121 Annotations ...... 123

• • • • 5 • • 1 – Table of Contents Carousel, User Guide

Buddy helpers ...... 123 Other helpers ...... 124 Logging ...... 124 Compilation and building...... 125 Switching toolkits ...... 125 Beyond the basics...... 126

SECTION III 127 13 Styles ...... 129 Using styles ...... 129 Changing a style ...... 130 Color schemes...... 130 Loading styles...... 132 Using System colors...... 133 Extended Styles...... 134 Applying styles ...... 136 Related issues ...... 136 Layout ...... 136 Flow ...... 137 Naming ...... 137 Data/formatting...... 137 Setting the system ...... 137 Setting the Look and Feel...... 137 Configuring Synth...... 138 SkinBuilder...... 138 Using styles with Synth...... 138 Using SVG and Synth ...... 139 Panel backgrounds ...... 140 Painters...... 141 Style guidelines ...... 142 14 Layout...... 143 Default layout...... 143 Limitations of explicit layout...... 143 Alignment tools ...... 144 Grids and Guides ...... 144 Guides...... 145 Adding guides ...... 146 Snapping to guides ...... 149 Snapping to hints...... 149 Setting up Columns ...... 150 Using guides...... 150 An example guide layout ...... 150 Reusing guides ...... 152 Layout managers...... 152 Component hierarchies ...... 154 Using a layout manager ...... 155 Framesets ...... 155 Editing framesets...... 156 Stopping home page from loading ...... 156

• • • 6 • • • Carousel, User Guide 1 – Table of Contents

Application Styles ...... 157 References ...... 157 15 Data binding ...... 159 Data binding...... 160 A simple static data binding ...... 161 Configuring the data source ...... 162 How the bindings work...... 163 Separating data from state ...... 164 Setting up a binding ...... 165 Update on page display ...... 166 Saving values ...... 166 Updating values...... 166 Source and output nodes ...... 167 Callbacks ...... 167 Dynamic bindings...... 168 Adapters ...... 168 Binding tables ...... 168 Selecting tables ...... 168 Linking components...... 170 Advanced attribute evaluation and libraries...... 172 Evaluated attributes ...... 172 Expression evaluators...... 174 Using evaluated attributes ...... 175 Adding new binding types ...... 175 Adding a configuration file...... 175 The configuration file format ...... 175 The structure of a data binding...... 175 Data binding adapter...... 175 Data binding lifecycle ...... 175 Data binding contexts and containers...... 175 Using the XModelHelper ...... 176 16 Event handling...... 177 Adding EventHandlers interactively...... 177 Basic event handling ...... 180 Built-in event handlers ...... 181 Accessing event objects ...... 181 Under the hood ...... 182 Custom event handlers...... 183 Exception handling ...... 184 Generic event handling...... 185 Extended Event Specification...... 186 17 Navigation and page management ...... 189 Navigation ...... 189 The page manager...... 190 Showing a page...... 190 Targets ...... 191 Page history ...... 191 Resetting the page cache...... 191 Page loaders...... 192 Dataset defined navigation...... 192

• • • • 7 • • 1 – Table of Contents Carousel, User Guide

Mapping page names...... 194 18 Application styles...... 195 Application styles ...... 196 Internal Frames...... 196 Docking Frames ...... 196 Using the docking layout ...... 197 Setting the layout configuration ...... 197 Docking options ...... 198 Embedded applications...... 198 Modular application ...... 198 Relaunching applications...... 199 Embedded webserver ...... 200 JNLP support ...... 200 19 Input validation ...... 203 Adding Basic Validations ...... 203 Adding component validations ...... 205 Validation attribute evaluation...... 205 Handling exceptions...... 206 Validation lifecycles ...... 206 Writing a custom exception handler ...... 206 Writing a custom validation factory and custom validations...... 209 Getting values from the XPage...... 212 Adding validation feedback ...... 214 20 Menus and toolbars ...... 217 Creating a Menu...... 217 Hooking up Events ...... 218 Toolbars ...... 221 21 Dialogs...... 223 Creating a dialog ...... 223 Structure...... 223 Display...... 224 Packing...... 224 Modality...... 225 Other issues...... 225 Setting the dialog location ...... 225 Centering the dialog on screen ...... 226 Resizable dialogs ...... 226 Titles...... 226 Helpers...... 226 Focus...... 226 Page activation ...... 226 Data bindings ...... 227 22 Localization ...... 231 The translation mechanism ...... 231 Choosing the language ...... 231 Setting the resource attribute for a page ...... 232 Changing languages in the application...... 233 Localizing the Language Chooser ...... 234 Scanning a project with the language editor...... 234

• • • 8 • • • Carousel, User Guide 1 – Table of Contents

Distribution of language files ...... 235 Encoding issues...... 235 Locale specific properties...... 235 23 The language editor...... 237 A quick tour...... 237 Elements of the language editor ...... 238 Choosing the languages ...... 239 Translation...... 239 Spell checking...... 240 Setup ...... 240 Database configuration ...... 240 Connecting to a database ...... 241 Starting a file based session...... 242 Choosing languages ...... 243 Configuring the spell checker...... 243 Starting a new project ...... 243 Opening a file...... 244 Adding a language ...... 244 Adding a new String...... 245 Adding a translation ...... 245 Substitutions...... 245 Special substitutions...... 246 Remote translation ...... 246 File formats ...... 246 Database table formats ...... 247 Flat file formats ...... 247 The language list (.lst) file...... 247 The language (.jln) file...... 247 The substitution (.sub) file ...... 248 Property files...... 248 Exporting to Microsoft Excel...... 248 Running the standalone editor ...... 249 Redistributing the language editor ...... 249 24 Data management ...... 251 Types of data...... 251 Resource access ...... 252 The data model...... 252 The DataSources ...... 252 Static data ...... 252 Tables ...... 253 Finding data...... 253 Loading and saving files ...... 255 Other data types...... 257 Databases ...... 257 Addings the database DataSource ...... 257 Configuring tables with the NetBeans...... 258 Binding to database tables...... 259 Drag and Drop data binding...... 260 Accessing database tables ...... 260 Distinct and other clauses ...... 261

• • • • 9 • • 1 – Table of Contents Carousel, User Guide

Filtering and finding rows ...... 262 Prepared statements...... 262 Adding data...... 263 Named connections...... 263 Configuring connections...... 264 Debugging...... 264 Databases ...... 264 Transferring data...... 265 Database synchronization...... 265 POJOs ...... 265 Hibernate ...... 267 25 Visualization ...... 269 Using the Visualizer within the Carousel Editor ...... 269 Debugging with the Visualizer...... 270 26 Evaluated attributes and helpers ...... 273 Evaluated attributes...... 273 Arguments allowed in XML attribute method calls ...... 273 Library expressions ...... 274 Expression evaluators...... 275 Using evaluated attributes...... 275 Escape sequence for path attribute values ...... 276 Handling evaluation exceptions...... 276 An example ...... 276 27 Introduction to routes and services ...... 279 Setting up a routing file...... 281 Setting up the Services file ...... 282 Saving a file using the FileSave route ...... 282 Opening a file using the FileSave route...... 285 Creating a custom ServiceProxy class...... 285 Building routes visually with Carousel ...... 288 Summary ...... 293 28 Advanced routes and services...... 295 Session Management and User Authentication ...... 295 Creating a custom client-server service proxy ...... 298 Using datasets to attach to a database ...... 300 Binding a ResultSet to screen components...... 304 Using KalIDEoscope to edit the routes ...... 306 29 Working with components...... 309 Choosing how to install components ...... 309 Using the registry editor...... 309 Installing a component factory...... 312 Setup the registration factory...... 312 Using reflection ...... 312 Using the new components ...... 313 Anatomy of a ComponentFactory ...... 314 A sample component...... 316 Special components...... 319 Hooking up a web browser...... 320 Adding a splash screen ...... 322

• • • 10 • • • Carousel, User Guide 1 – Table of Contents

Swing splash screen ...... 324 Component customization ...... 325 Using Drag and Drop...... 326 30 Using SVG graphics...... 329 Choosing how to install components ...... 329 Component details...... 329 31 Printing and export ...... 333 Direct printing ...... 333 The printing infrastructure ...... 333 Creating print forms ...... 334 Printing tables ...... 334 Other printout issues...... 335 Outputting to file ...... 335 Printing via Excel ...... 342 Printing and interacting with OpenOffice...... 343 Printing via HTML...... 343 32 Drag and drop...... 345 Enabling drag and drop...... 345 Customizing drag and drop...... 345 Drag and drop and data bindings ...... 347 Drag and drop and components...... 347 Extending drag and drop ...... 347 Registering new flavors ...... 347 Drag enabling new components...... 347 33 Importing HTML ...... 349 Opening HTML within the IDE ...... 350 Using the HtmlBuilder ...... 350 Customizing the HtmlBuilder...... 350 34 Importing forms ...... 353 Opening HTML within the IDE ...... 354 35 Packaging and deployment...... 357 Package your project...... 357 Running a Carousel application from the command line ...... 359 Running a Carousel application using Java Web Start...... 359 Setting up a JWS extension...... 362 Deploying a webstart application via CD ...... 362 Running a Carousel application from a web page...... 363 Creating a setup for your Carousel application ...... 363 36 Compile, build and test ...... 367 Debugging ...... 367 Beyond logging...... 368 Debugging with NetBeans ...... 368 Using JBuilder...... 370 Automating testing ...... 373 37 Troubleshooting ...... 375 I’ve built my application but it doesn’t run ...... 375 Only part of my page is appearing...... 376 The 3d effect on buttons is missing...... 377

• • • • 11 • • 1 – Table of Contents Carousel, User Guide

I get an exception when using Synth...... 377

SECTION IV 379 38 Carousel UI Components...... 381 Graphical Components...... 381 XShape ...... 381 XEasterEgg ...... 384 XReflectedImage...... 384 XCaptionedImage ...... 385 Text Components ...... 386 XFlowedTextComponent ...... 386 XHtmlText ...... 388 XPolygonalTextArea ...... 389 XReflectedText...... 391 XRotatedText ...... 392 Animations ...... 393 XAnimatedText...... 393 XCreditsText ...... 394 XMarqueeText ...... 395 Input Controls...... 395 XBaseTable...... 395 XCheckList...... 396 XDateEdit ...... 397 XKeypad...... 397 XMoneyEdit...... 398 XSpinner...... 398 XSlider...... 398 XProgress...... 399 Data Components...... 399 XGraph...... 399 XTreeTable ...... 407 Multimedia Components ...... 409 XAudio ...... 409 XVideo ...... 409

SECTION IV 411 Mortgage application 413 Introduction...... 413 Introduction tutorial...... 414 Advanced Tutorial ...... 419 Bindings ...... 420 Navigation...... 422 Framesets and component registration ...... 424 Dialogs...... 425 Wizard application 427 Introduction...... 427 Framesets and pages...... 428

• • • 12 • • • Carousel, User Guide 1 – Table of Contents

Navigation ...... 430 Component Registration...... 434 Validations...... 437 Data binding...... 442 Localization ...... 446 The Synth Look & Feel ...... 450 ...... Surveys 453 A typical survey ...... 453 A welcome screen...... 454 A survey wizard ...... 455 Managing the survey data ...... 458 Setting up survey templates...... 459 Embedding a survey...... 459 Setting up a survey database ...... 459 Configuing a survey ...... 459 Using rules...... 459 Product selection 461 Building CoolSelector with XUI ...... 461 Background...... 461 Part of the inspiration for XUI...... 461 Description of the Existing system ...... 462 Room for improvement...... 462 The XUI experience ...... 463 Comparisons...... 463 Results ...... 464 Features ...... 464

SECTION VI 471 Appendix A — Architecture ...... 473 The XUI Solution ...... 473 Project support for coordination of resources ...... 474 Factory methods to remove repetition ...... 474 Factories to target different devices/platforms ...... 475 Full API access ...... 475 Layered approach to styles ...... 475 Modular extension ...... 476 Page management...... 476 XML as a shortcut to declaring content...... 477 Proxies for event management ...... 478 Input validation...... 478 Data modelling ...... 479 Data loading ...... 479 Data binding ...... 480 Database access ...... 481 Services and communication...... 481 Routing ...... 482 Resource Loading...... 482 MVC pattern for separation of concerns ...... 483

• • • • 13 • • 1 – Table of Contents Carousel, User Guide

Appendix B — Java language ...... 485 Don’t forget you can use Java ...... 485 Object types ...... 485 Inheritance ...... 486 Package Names ...... 486 Classloaders...... 487 Reflection ...... 488 Encodings...... 488 Annotations ...... 489 Learning Java ...... 490 Further Resources ...... 491 Appendix C — Startup properties ...... 493 Properties ...... 493 Appendix D — Embedded support ...... 497 Choosing the JDK ...... 497 Choosing the right libraries...... 497 Rebuilding the libraries...... 497 Removing the shutdown hooks...... 497 Real-time support...... 498 Appendix E — Reference...... 499 Component attributes ...... 499 Appendix F — Upgrading...... 505 Projects ...... 505 Projects ...... 505 XPage split...... 506 ComponentAdapters...... 506 Widening of methods ...... 506 Page references ...... 506 New features ...... 506 Deprecation...... 507 Omitted components...... 507 Appendix G — Building XUI ...... 509 Accessing SVN ...... 509 Preparing to build...... 510 Building...... 510 Appendix H — Kalideoscope for Eclipse ...... 511 Installing the plugin ...... 511 Creating a new project...... 511 Accessing SVN ...... 514 Preparing to build...... 515 Building...... 515 Appendix I — Widgets Sets ...... 517 Widgets sets ...... 517 ...... 517 AWT...... 517 SWT ...... 517 HTML...... 517 J#...... 518

• • • 14 • • • Carousel, User Guide 1 – Table of Contents

Others...... 518 Widget abstraction ...... 518 Portable coding...... 518 Design considerations ...... 518 Modularity ...... 518 Finding a JVM ...... 518 Appendix J — What’s new in version 3.0 ...... 519 New features...... 519 New XUI features...... 519 New Kalideoscope features ...... 530 New Carousel features ...... 533 Upgrading your project...... 534 INDEX 535

• • • • 15 • • 1 – Table of Contents Carousel, User Guide

• • • 16 • • • SECTION I BACKGROUND 1 – Carousel, User Guide

• • • 18 • • • 1 – About this book Carousel, User Guide

1 About this book

This user guide provides information on using and developing applications with Carousel. The guide is organized into an number of sections. Section I Begins with an introduction to Carousel, its history and its position on the technology landscape. Section II Describes the Carousel Integrated Development Environment (IDE) and the basic features that are commonly included in an application are explained. Section III Covers more advanced features and the features that are required to build full- featured client-server applications. Section IV Illustrates many features by way of case studies. The guide then concludes with a selection of reference materials. Xoetrope also provides step-by-step tutorials, courseware and on-line reference manuals so the focus of this manual is on explaining the concepts of developing applications with Carousel. The Xoetrope web site also features a developer zone where you can find working applications and numerous technical articles.

User Guide Conventions

The documentation for Carousel uses the typefaces and symbols described in the table below to indicate special text.

Typeface Meaning

Monospace type Monospaced type represents text as it appears on screen or in Java code. It also represents anything you must type.

[] Square brackets in text or syntax listings enclose optional items. Do not type the brackets

<> Angle brackets in text or syntax listings indicate a variable string; type in a string appropriate for you code. Do not type the angle brackets. Angle brackets are also used for HTML tags.

... An ellipsis in syntax listing indicate code that is missing from the example.

Table 1-1 — Document conventions

• • 19 • • • • 1 – About this book Carousel, User Guide

Typeface Meaning

Italics Italicized words represent Java identifiers, such as names of variables, classes, interfaces, components, properties, methods, and events. Italics are also used for new terms being defined

Keycaps This typeface indicates a key on your keyboard for example, “press ESC to exit”.

Table 1-1 — Document conventions

XUI and Carousel

Carousel is a commercial platform from Xoetrope that extends the libraries and the editor facilities available in the open source XUI platform. Some sections of this user guide are specific to Carousel. Wherever sections are specific to the Carousel platform you will see a note is italics at the start of the section or chapter indicating that the following content refers only to Carousel. Carousel is built upon XUI and therefore anything that can be done with XUI can be applied just as well to Carousel. The commercial Carousel specific libraries begin with the com.xoetrope package name whereas the open source libraries begin with the net.xoetrope package.

Contacting Xoetrope developer support

Xoetrope offers a variety of support options. These include free services on the Internet, where you can search our information base and connect with other users of Xoetrope products. in addition you can choose from several categories of telephone support, ranging from installation support to fee-based consultant-level support and detailed assistance. For more information about Xoetrope’s developer support services, see our website at http:// www.xoetrope.com. When contacting support, please be prepared to give complete information about your environment, the version of the product you are using, and a detailed description of the problem.

• • • 20 • • • 2 – Introduction Carousel, User Guide

2 Introduction

Carousel is a Java and XML framework for creating applications with rich user interfaces. Carousel includes a plugin for the netBeans integrated development environment making the development and testing process as easy as possible without locking you into a proprietary solution. Carousel also has a rich set of libraries, tools and wizards for rapid application development.

Note: XUI (pronounced zo’i) is the open source platform upon which Carousel is in part based. Carousel greatly extends XUI and includes many features and facilities not available in XUI. Much of this document can be used as a reference for XUI. Features and chapters specific to Carousel will be noted at the start of each affected section.

What is Carousel?

First and foremost Carousel is a framework for building Java and XML based applications. The aims of Carousel are to: • Reduce the amount of code needed to build an application • Provide a clean application architecture and infrastructure • Simplify building and maintaining applications • Allow easy extension and customization • Enable lightweight and performant applications The core of Carousel is a small Java library that allows 'pages' of an application to be constructed from an XML declaration or from Java code. Carousel offers many add-ons and extensions including a graphical editor/IDE. Carousel is commercial software extending the free open source software (FOSS) editor offered under the Xoetrope Public License (identical terms to the MPL) as part of the XUI platform. This license allows for Carousel to be used in commercial applications without the restrictions of some of the more common OSS licenses.

• • 21 • • • • 2 – Introduction Carousel, User Guide

The relationship between XUI and Carousel is shown below. XUI builds upon the Java platform, Carousel builds upon XUI and in turn your application can build upon all of these technologies.

Figure 2-1 — Carousel-XUI-Java

Carousel can be used for simple single page applications and forms or for complex business applications comprising many page and resources.

What can be built with Carousel?

Carousel can be used to build a wide variety of applications just a few of which are listed below: • Simple form based applications • Catalogues, Configurators, Browsers • Selection tools • Guides/Brochures • Retail and Point-of-Sale applications • Kiosk applications • Mobile applications for field workers and road warriors • Surveys and market research applications • Database applications • e-learning applications • Informational and promotional applications

• • • 22 • • • Carousel, User Guide 2 – Introduction

Carousel is a general purpose tool so it can be used to build just about anything you can imagine building with Java and XML, but it offers the greatest advantage when building client side applications.

Figure 2-2 — Rich-client platform landscape

Carousel also includes many sector specific features and add-ons. The Xoetrope website has a full list of the add-ons and case studies highlighting how Carousel’s has been used to build specific solutions.

What does Carousel do?

In a nutshell Carousel can be used to build feature rich, smart-client applications. Smart client applications are typified by their ability to make use of client-side computing power. Notably this means that such applications exhibit; • A feature rich user interface • A fast and responsive user interface • Ability to work on-line or standalone • A simplified application construction • Ease of updated and processing of dynamic content • Built-in data management • Sophisticated functionality • Optimized bandwidth usage • Low maintenance and administration characteristics All of these features can be found in Carousel built applications. Furthermore, being Java and XML based, Carousel applications are portable so that they can run on a wide variety of devices and platforms.

• • • • 23 • • 2 – Introduction Carousel, User Guide

As a development platform Carousel leverages the usual drag and drop techniques to make building applications quick and easy. Carousel includes numerous widgets, library functions and wizards to make many common tasks simple. Simplicity really is the key to Carousel, so even if the feature or behavior you desire isn’t predefined it usually isn’t difficult to implement. As an open system Carousel even allows such additions to be made in a reusable way so that you may only need to define the addition once. Even if you need to go beyond Carousel’s capabilities you can work directly with Java and XML or with third party tools. So, ultimately Carousel make the developer’s life easier.

How does Carousel work?

Carousel takes advantage of local computing resources. So, instead of going back and forth to a server a Carousel application can store and process information. As a result you don’t see the delays that are typical of some web-based applications. Using the local computing resources means that you can make an application more responsive, offer more and better user interaction and build smarter applications, so-called rich-client applications. Making use of local computing resources also helps simplify some of the tasks involved in building modern software applications. If you don’t have to go back and forth to a server for information you don’t need to do so much to maintain state information. Furthermore if you can eliminate input errors at source then your business processing should be less complicated.

Figure 2-3 — MVC Architecture

In addition to the implicit benefits of a rich-client framework Carousel also applies some well known architectural techniques to further simplify the process of building applications. The most important of these concepts is the Model-View-Controller (MVC) pattern. With this pattern the key components of an application are separated from one another to simplify development. In Carousel the MVC architecture is promoted by the natural separation of the various components in framework and by the coding styles and techniques used for each component.

• • • 24 • • • Carousel, User Guide 2 – Introduction

The Carousel MVC components equate to • View: Pages defined in either XML or Java. • Model: The data, declaratively bound to the pages or view. • Controller: The application logic specified in Java and declaratively bound to the other components. Carousel also supports declarative user interface specification and declarative data binding whereby pages, data bindings and event bindings can be specified in XML independently of one another. The late coupling this provides has a number of benefits. Pages can be delivered or updated independently of one another much like HTML pages. This sort of independence of content was one of the major benefits of thin-client and web applications yet Carousel manages to deliver similar behavior and benefits in a rich-client framework. Carousel however achieves this while leveraging the Java platform, in the process delivering efficient, modular and reusable components. Much of Carousel’s benefits stem from this loose coupling of components. Since the View is loosely couple to the data model a new look and feel can be placed on an application with minimal implications for the application behavior or coding. Similarly the application logic can be coded with minimal reference to the user interface or how data is bound and update to that user interface. Imagine being able to write the code for even a simple equation without having to know when or how the input fields are filled out or how to then display the results of your calculation. The separation of roles pays dividends in a number of ways. People of differing skills can Fixing a bug in say the collaborate on a project with perhaps one concentrating on the user interface and visual side business logic is while another may be responsible for business considerably easier logic or data processing. Whether this is actually a realizable business benefit is a moot point, but in when you don’t risk the long-run the benefits are very real. In a maintenance mode it may be many months breaking the user since a particular feature or aspect of an interface. application has been developed. Being able to ‘fix’ a bug in say the business logic in such a feature is considerably easier when you don’t risk breaking a user-interface feature or the data setup or vice versa. Furthermore without mixing user-interface code and business logic the role and intent of each piece of code is more apparent and this make understanding each part of the application a little less involved. Carousel is in some senses is a fairly typical development environment or framework for building Java applications, a plug-in for the NetBeans IDE is even a key feature. Carousel however aims to make the process of building and maintaining applications as simple as possible. Using the techniques described above Carousel eliminates much of the normal ‘plumbing’ code and allows you to get on with building real value into your application. In saving large amounts of coding the burden of developing and maintaining applications is also greatly lightened.

• • • • 25 • • 2 – Introduction Carousel, User Guide

Licensing

Carousel is available under the open source GPL license which allows developers to download and try out the software. A GPL version of Carousel may also be included in another GPL application, but for commercial uses most users will want a commercial license. Commercial licenses are available from Xoetrope without the restrictions of the GPL. XUI is available under the Xoetrope Public License (XPL - identical to the Mozilla license in all but name, as required by the MPL). Any enquiries about licensing can be addressed to [email protected].

• • • 26 • • • 3 – Why Carousel? Carousel, User Guide

3 Why Carousel?

Carousel started out as a simple editor designed to make life easier for the developer. The XUI library had helped make construction of the user interface (UI) simple and in Carousel this ease of use had been extended to include many of the features needed to build rich enterprise level applications. The modular nature of the framework meant that inevitably there was some configuration required, Carousel was therefore born to assist in the setup and configuration of such applications. Over time Carousel has developed to include a range of advanced features and tools that ease the task of building modern applications.

Background

Carousel is a Java-based system that sets out to solve many of the problems encountered when building Rich Internet Applications (RIA). Users are demanding more features, more performance, better integration and generally greater usability from their applications. A competitive market and demanding users means that modern applications are becoming more and more complex, often to the point where development is at the limit of the available resources and maintenance is highly expensive. For the many organizations this complexity may translate into less that ideal behavior or reduced functionality within the application. While Carousel is based upon Java, Java in its basic form can be misused, and to some extent Java suffers from some shortcomings from the application developer’s perspective in that there is no out-of-the-box support is included for high-level abstractions such as the MVC architecture, and there is little high-level support for communication and data-access, and in some cases excessive plumbing is often required to perform simple tasks. Carousel aims to eliminate much of the plumbing involved in building RIAs, so that the developer can concentrate on adding value to the application. Many of today’s client applications, be they built on Java or not, suffer from code bloat and poor maintainability. Poor maintainability often derives from the use of IDEs and the throwaway nature of the code they generate. Unaddressed, this lack of emphasis on good design and quality leads to poor performance. For many, this poorly constructed application type is typified by the monolithic fat-client application, with all its deployment and maintenance issues. One common solution to the problems of fat clients is to employ a thin-client architecture, moving processing to the server side and removing client administration woes, yet this solution is not without its own perils. Shifting the problem of poor design to the server won’t win many awards and introduces many of its own problems, like security and session handling, not to mention performance.

• • 27 • • • • 3 – Why Carousel? Carousel, User Guide

Hybrid application types like Ajax share most of this thin-client legacy but added apparent interactivity, however, this comes add the price of even greater complexity and all without the architectural merits of either the fat or thin client application. Ajax applications also suffer from a lack of tooling, whereas a typical Java developer will have an abundance of superb tools. Despite the poor reputation gained by some client applications, there has been a resurgence of interest in smart client applications. Most client devices, even handheld devices, now have sufficient processing capability to perform useful work and this is wasted in a thin-client environment. Many of the fat-client problems have been solved and the thin-client solution is not the panacea that many had desired. The XUI library at the core of Carousel is an open-source framework designed to solve some of the problems involved in building modern smart client applications.

Why do we build applications at all?

It may seem obvious to say that we build application to meet business needs, yet it is worth reflecting on the bigger picture. What do we hope to accomplish with our applications? Typical requirements include getting the work done in an efficient and effective manner and having a reliable and maintainable system. All quite straightforward, but what about keeping the customer happy? Quite often the job is not just about getting the immediate business done but also about keeping the customers happy. Many of today’s applications fall short of providing an all round satisfying user experience. Frequently the user simply wants to accomplish the task at hand with the least amount of pain. At other times the user wants a richer, more informative experience, one that adds value. Carousel can help you provide fast and effective client solutions.

The Form Metaphor

According to 2001 analyst estimates American businesses alone spend upward of $15 billion transferring data from paper-based forms such as loan applications and purchase orders to their computer systems. Billions more is invested every year in web based forms and other electronic forms. Not surprising when you consider the ubiquity of the humble form. Almost every business process involves form processing of one sort or another. In a broader view forms are an essential part of the data capture process for many businesses. Electronic data capture and form processing offers many advantages over paper alternatives and act as the basis for a wide range of business applications. In many cases it may not even be possible to achieve comparable results with a paper based approach. Electronic forms can be of great value to both the end user (ease of use and error checking) and for backend processing (speed, quality and security). Today a wide range of technologies are available for electronic forms processing. Many of the newer technologies are enabling completely new areas of automation and better, more functional applications. Couple this with other related technologies like mobile computing and wireless communication and you have many exciting new opportunities for improving workflow and communications.

• • • 28 • • • Carousel, User Guide 3 – Why Carousel?

From a business perspective automated form processing can bring many returns above and beyond the direct savings. The improved data can lead to better analysis of the customer relationship. Closing the enquiry-sales-fulfilment loop to manual data entry can even reduce leakage from the sales cycle. Where field workers or representatives are involved, faster more efficient technology will empower the employee. In an application context the notion of a form can be quite vague but for the purposes of this guide we will assume that a form is a fairly discrete component that helps capture a subset of data. How that form is presented to the user can vary greatly within the definition of the user interface but from the point of view of the application logic the form’s role is fairly well defined and helps for a logical subdivision of an application.

Beyond Forms

HTML forms have been the mainstay of web The mix of HTML, applications for some time. Although forms can be considered a workhorse of data capture, their use as JavaScript and server the de facto user interface is not particularly well side technologies can suited to the demands of modern business processes or for more complex application design. It is common for rapidly lead to applications to comprise whole sets of forms and much of their value comes from relating the information on complex technology one form to another and to business intelligence. It is easy to see that the smarter an application appears and the more responsive it is to the user, the richer the experience. Many of the web technologies in use today go to great lengths to provide such responsiveness and such intelligence, yet in many ways they face an uphill struggle. The infrastructure required to deploy some of these frameworks can be significant and rapidly pushes up the total cost of ownership despite what may be the obvious technical merits of an individual technology. HTML was designed primarily for the display and linking of static text and static content. Extensions, plug-ins and many server side technologies have added to the power and capability of the basic HTML technology. The so called thin client that these technologies popularized has gained enormous popularity over the last few years. Despite the ubiquity and popularity of the thin client there are many areas where these web technologies have been less successful.

HTML’s limits

An HTML application or form normally requires a request to the web server to provide updated content. Plug-ins or scripting may be used in some situations to avoid the round trip to the server and provide some element of local interactivity but often at the cost of complexity. For anything other than simple applications the mix of HTML, JavaScript and server side technologies can rapidly lead to a complex technology solution. In many ways the solution is often more complex that the original problem. The more complex the applications become the greater the strain for these solutions to be effective.

• • • • 29 • • 3 – Why Carousel? Carousel, User Guide

Even without the implementation and delivery issues, HTML based applications suffer from the inherent delays associated with having to make frequent requests to the server. A simple round trip leads to noticeable delays in responding to user interaction and hence there is a limit to what is effective in terms of user interactivity with such applications.

Scripting

One of the defining characteristics of many web frameworks is the use of client-side scripting technologies. While scripting may be acceptable for small scale use it does not work well for large scale use. Scripting lacks many of the object-oriented features that programmers expect of a modern platform. Couple this to the common problem of separating roles with a environment that normally sees scripts embedded in user interface declarations and you can end up with a complex mess. Underlying HTML’s use is of course the browser, with all its security restrictions and compatibility problems. Even within an individual browser the lifecycle of a page can prove troublesome, making it difficult to maintain state. HTML is just not a natural fit for the needs of many modern applications.

Figure 3-1 — The client-server landscape

Application delivery in a connected world

Today, a new range of connected workers has emerged, the road warrior, the business traveller, the salesman, the field worker, the PDA/Smart device owner. This type of user

• • • 30 • • • Carousel, User Guide 3 – Why Carousel?

presents many new challenges. Typical of these demands is the occasionally connected nature of their usage. It’s not much good to have smart devices if it is assumed that the application software needs constant connectivity, or if the applications cannot cope with loss of connectivity mid session.

Rich Client to the Rescue

Desktop computers and even the majority of mobile devices have significant computing power and therefore it is well within their capacity to handle much of what is delegated to the web server by thin client applications. One of the cornerstones of performance is locality of computing. Holding true to this maxim, locality of computing for a form application means that such things as data validation, prompting, user interaction can be handled locally. Doing things locally means not having to wait for a round trip to the server to complete. This alone can lead to faster, more interactive applications and interacting with data locally can also facilitate disconnected and mobile applications. Add to the local interactivity the rich user interfaces that can be built for today’s rich client applications and you can get some very attractive applications.

So Why Carousel?

Carousel is a rich client application development platform designed to improve the way in which Forms and internet applications can be built. Bringing together two powerful technologies, Java and XML, Carousel offers many advantages in terms of ease of development, Carousel is designed to performance and portability. These advantages lead directly to reduced development and improve the way in maintenance costs. The rapid development process that Carousel enables also means that you which forms and internet may have more time to devote to improving applications can be built. content and creativity. The open source XUI framework addresses many of the problems discussed above and then some more. Carousel adds many additional widgets for building applications and business sector specific features and wizards, not found in the basic open source platform. Carousel also provides client-server support so that applications can more easily work within a corporate environment and communicate with back-end services. Carousel comes with a feature packed editor and is built in an open way, supporting open standards. Vendor lock-in is avoided and the editor can be used in conjunction with other tools. So even if your authors and developers don’t want to use low level technologies like XML they can build applications with the familiar drag and drop metaphors.

The Development challenge

For many organizations the move to thin clients was driven by administrative issues as much as implementation ones. The thin client was seen as a way of reducing administrative and helpdesk requirements as the client application had zero footprint. Furthermore the assumed ease of updating content was considered a major benefit in itself.

• • • • 31 • • 3 – Why Carousel? Carousel, User Guide

The penalty for this approach was that more responsibility was placed on the server side. All the users, all the user information and preferences had to be managed by the server. All the processing was shifted to the server as well. While architecturally this structure may have seemed simpler it often involved several tiers and a large array of systems. The return of the rich client will not do away with many of the demands placed on today’s servers but it will certainly reduce the load and in many ways simplify the applications. With each client managing its own state the server can be focused on providing the centralized enterprise level facilities to which it is best suited. A rich client framework like Carousel implemented in a single language is considerably simpler than the highly layered approaches common in today’s thin client systems. The problems that dogged rich clients of the past are but a memory. Zero footprint and incremental updates are a given. Security and a richer user experience are bonus. Individual features of Carousel are worth using on their own not to mention using them in concert with other Carousel features. Take for example Carousel’s method of constructing user-interface components via factories. This feature alone saves large amounts of code over what would be generated by a typical IDE. Carousel is a modular system so you can employ just one feature like this on its own, mixing and matching to your needs. Carousel, can therefore be integrated into new, old or legacy applications without difficulty. For legacy applications the Carousel framework can provide a convenient way of adding new and modern features to what may otherwise be tired looking applications. Above all Carousel is designed by programmers for programmers.

• • • 32 • • • 4 – Related technologies Carousel, User Guide

4 Related technologies

Carousel is built upon an open architecture and hence it can support a wide variety of technologies. Equally Carousel can be used in an ad hoc manner whereby parts of the package can be used and other parts replaced or supplemented by other technologies. Carousel was designed to support good programming practices and the use of best of breed tools so in many ways the technologies listed in this chapter need not be seen as competing technologies and can be used comfortably alongside Carousel.

Carousel versus HTML

HTML is well known and can be used for a wide variety of presentations and even for simple form applications. However HTML is not well suited to anything other than trivial applications. The mix of HTML with the scripts typically needed for interactive web pages can be a nightmare to develop and maintain. The scripting code tends to get heavily embedded in the HTML and it is therefore difficult to decipher and reuse. Numerous attempts have been made to address the needs of web applications but many of these attempts require large plug-ins or are restricted to a Windows platform. We believe that Carousel strikes a good balance, requiring no plug-ins, a small download requirement, pages that can be downloaded individually or en-masse all while still managing to have powerful programming capabilities. The XML used by Carousel is easy to read and understand. Separation of the scripting means that The full power of Java the XML is clean and compact; ideal for offloading to a graphic designer if so desired. The Java code is available to a used in place of the XML can run in the browser’s Carousel application. native environment and is pure code, again no mixing of content so from the programmer’s perspective this too is desirable.

Carousel versus AJAX

AJAX isn’t a new kid on the block, having been around in many guises for several years. AJAX is essentially a technique for updating a web page without having to request a page refresh. AJAX can update a fragment of the page and the end user has the impression of a more responsive environment as only some of the page updates. Indeed AJAX may be a little more

• • 33 • • • • 4 – Related technologies Carousel, User Guide

efficient than vanilla HTML as the fragments of HTML/XML it pulls down during updates will conserve some bandwidth. AJAX can enable some client side processing of data but it is at heart still a scripting technology, still burdened with all the drawbacks of scripting and of being browser based.

Carousel versus Java

So why not program in Java? Carousel’s use of XML makes it compact and simplifies the process of creating forms and more generally simplifies the creation of a UI. The separation of concerns means that the core business logic can be separated from the UI with the consequence that the code is easier to develop and maintain. Not only that, but the code is also more likely to be reusable. In comparison to a Java solution developed with a typical integrate development environment we normally see a reduction of 50-70% in the size of the codebase. Despite the benefits that Carousel can bring we do not mean to suggest it can do everything. Java is a very powerful programming platform and Carousel has been designed to work with Java and therefore the full power of Java is available to a Carousel application. Careful coding means that Carousel can run with the browser’s built in Java support (JDK 1.1.4 of Internet Explorer) and on a wide range of mobile devices. The result is that you aren’t really faced with the choice of Java or Carousel; rather you have the option of using the best features of both systems to give a powerful small footprint system. Sun’s Swing and NetBeans teams continue to make great strides in improving the Java desktop experience, however, most of the new technologies they introduce require a recent JDK and this may not be available to everyone. Most of Carousel’s technology is available on a wide range of JVMs. Despite the overlap between Carousel and some of the newer Swing features we plan to support emerging technologies as they mature and become available, particularly where they are standardized. Carousel 3.0 introduces a new application architecture to make it easier to customize the basic application startup and behavior, and in this respect additional support for Swing has been added by way of a new startup object that can essentially integrate a Carousel application as a component within a run-o-the-mill Swing application. Carousel 3.0 also extends the Swing widget support, making use of third party Swing components very simple. So what does all this mean? Well Carousel and XUI play very well with Swing and standard Java desktop technologies. For the most part you can view Carousel as a code saving technology for Swing, and after that you can use the normal Swing coding conventions.

Carousel versus Servlet and Server Side Technologies

A number of server side technologies have been used to assist in the development of web applications. The Apache Foundation has produced several of these libraries, notably the Struts library. Sun, Microsoft, IBM, Oracle and others have added to the range of server side technologies available to the developer. The various technologies that these tools offer almost all produce HTML or XML that is rendered on the client. The server side tools add many facilities for validation of data and control of the client integration with the server but

• • • 34 • • • Carousel, User Guide 4 – Related technologies

on the whole they fall short of offering the type of rich client that can be built with Carousel and the client side technologies outlined above. Of course most modern applications rely on a server side process to implement key business functions. Carousel is no different and in this sense it is Not everyone has the complementary to server side technologies. However Carousel relieves the server of the luxury of starting with challenges involved in much client state a clean slate, Carousel information. Carousel can integrate with business components on doesn’t necessitate such the backend via a variety of protocols and processes, an approach. be that simple HTML forms, J2EE, Soap or .Net. Carousel’s service model neatly encapsulates these services so that the much of the detail can be hidden from the application programmer. Not only can you choose Carousel and/or Java but using XML you can easily move from AWT to Swing, without recoding, so for a Windows user this means it is possible to run with Internet Explorer without need for additional downloads or plug-ins. Support for other widget sets (e.g. LCDUI/Blackberry) is being developed from prototype). Carousel versus .NET Microsoft’s .Net platform has been gaining widespread coverage and Microsoft has made some forays into the forms market. Carousel can be run on this platform via the J# language (a clone of Java) if required. On some mobile platforms this may be desirable where a JVM is not available or is a cost impediment. However Java is by far the more mature platform and the available resources are far more extensive. In using .Net there is also the risk of getting locked into a Microsoft environment and the consequent costs. At the core, Carousel being an open source platform gives you plenty of options. Carousel versus XUL , XForms, XAML et al Mozilla, Microsoft and others have produced a variety of XML formats for user interface description. These formats share many of the same objectives as Carousel and unsurprisingly they use many similar techniques to construct applications. One of the advantages of XML in this context is that the formats are relatively open and so it is possible to render these documents with the Carousel add-on libraries published by Xoetrope. Carousel differs from these libraries in a number of key ways. Firstly XUL and its variants rely heavily on client side scripting making them more difficult to program and maintain than the pure Java used in Carousel. Many of the XUL variants are rendered with the Java Swing library making them unsuitable for resource challenged situations such as exist on mobile devices, Carousel can be rendered with the AWT and hence memory and bandwidth are conserved. And of course XUL can’t be compiled so it always pays the cost for parsing Microsoft’s XAML format deserves separate mention even though it is in many ways similar to XUL. XAML of course is not yet widely available. The licensing model offered by Microsoft may make use of XAML prohibitively expensive and the availability of XAML clients may be limited to the very latest Windows desktops. Of course given Microsoft’s strength in the market place the impact of Longhorn and XAML will be significant. The XAML architecture mimics that of Carousel in many ways and

• • • • 35 • • 4 – Related technologies Carousel, User Guide

provides many of the same features and facilities so we take this as an endorsement of the Carousel architecture. In many ways Carousel does for Java what XAML does for Windows. The World Wide Web consortium is promoting XForms as part of the XHTML standard and again this offers a variation on the XUL theme. XForms embodies a rich data model and supports lifecycle semantics for a rich web client. Like XUL, XForms relies heavily on scripting, although to a much lesser degree than HTML forms. Again the add-on Carousel libraries can render and interoperate with XForms. Carousel differs in that its data model and update semantics are more cleanly separated in the industry standard MVC architecture making for a clean maintenance structure and clear programming structures. A prototype filter is under development that allows Carousel to read formats such as XForms, Infopath and XAML. Carousel versus Ajax Ajax is something of a juggernaut powered by the hype surrounding Tim O’Reilly’s Web 2.0 notion, however Ajax has been around quite some time and even featured in a precursor to XUI and Carousel. Without doubt, Ajax is an improvement on vanilla HTML and even DHTML, but as has been mentioned above this comes at a price. Ajax applications are often quite complex, having a mix of client and server side technologies and a mix of programming metaphors and language. While this might be highly important to developers, end users probably couldn’t care less about this complexity, so long as they can get the job done. Therefore Ajax has alot of merit and may well be the best choice for some applications. Conversely as applications grow and the shortcomings of the Ajax platform begin to exhibit themselves then a XUI or Carousel based application begins to become more attractive. Quite often the power user will demand better performance or better desktop integration than can be delivered by Ajax and here Carousel can help. Therefore, if the system is not too complex and there is only occassional or light use of an application then Ajax could be a good choice. Where performance, or integration, or flexibility, or complexity are bigger issues then Carousel may be the better option. What may surprise some, who wrote of Java as slow and clunky, is that a Java application like Carousel can be visually attractive, with lots of rich user interface features and great performance. Where that visual impact is important Carousel is also the better option.

Other issues

The technology used in Carousel is only one part of the overall application development story. There are many factors that affect how a project is implemented and managed. The following sections highlight some of these important factors to consider when embarking on a development project of any significance. Legacy application support Not everyone has the luxury of starting with a clean slate, and importantly Carousel does not necessitate such an approach. The open architecture employed by Carousel makes it easy to use Carousel when and where possible. This may simply be the use of Carousel to cleanup some code or it may be more extensive. Carousel can be added incrementally to a project. Legacy applications frequently suffer from maintenance issues such as spaghetti like code and the mixing of concerns so that it is often difficult to identify key business logic. Carousel can greatly simplify this code by allowing much of the plumbing to be removed or hidden. Not

• • • 36 • • • Carousel, User Guide 4 – Related technologies

only does this save code and reduce the complexity but it also make the business logic more apparent. But why fix a working system? It’s quite simple really; it’s easier to maintain a small code base than a large one, and it’s easier again to maintain a clean code base than a convoluted one. Using Carousel as part of the cleanup means that the real value in an existing application can be preserved and prepared for tomorrow’s challenges rather than facing a rebuild. Carousel’s support for new technologies like POJOs, data binding and modern user interface components also mean that Carousel can be a good choice for extending, reviving or refreshing existing applications. Simple single language support Many of today’s applications and systems are composed of a variety of subsystems, often in different languages and invariably requiring multiple developers with different skill sets. In contrast Carousel has a single language implementation. Java is used throughout and can be supplemented with simple XML (and this XML can be hidden from sight by use of the IDE). Separation of roles Carousel promotes a clean architecture by separating development roles and concerns. As has already been remarked Carousel makes business logic stand out by removing plumbing code. Carousel goes further by separating the applications data, services and user interface into distinct components. Not only does this facilitate maintenance but it also helps promote good development practices. Occasionally connected Modern applications have to cope with a wide variety of connected devices. Despite the ubiquity of internet access it cannot be assumed that there is always a connection available. Even if there is a connection available quality of service considerations, or security concerns may mean that an application must cope gracefully with intermittent connectivity. Carousel not only supports this capability but provides sophisticated mechanisms for handling remote communications, routing and fault tolerance. Added to this is Carousel’s ability to support store and forward mechanisms so that once connectivity becomes available data can be sent to the server or updates retrieved. Branding Many companies sell through channels and these channels require branding of the application to suit the channel. Carousel stylesheets facilitate this rebranding without change to the code. Within Carousel you can easily replace colors, fonts, text and other resources. This together with the separation of concerns enforced by the MVC architecture means that you can efficiently build an application to support multiple brands or sales channels. Furthermore the open architecture means that it is possible to deliver modular solutions whereby resellers and related businesses can integrate content in a coherent manner. Performance and server load Because Carousel promotes the idea of a rich client and of performing more processing on the client side there is a consequent reduction in the load on the server. This locality of

• • • • 37 • • 4 – Related technologies Carousel, User Guide

computing also leads to direct performance gains from a user perspective. Local calculations may not require a round trip to the server for data retrieval and once retrieved the data can be accessed efficiently. Moving processing to the client also removes several layers of processing (security, load balancing, logging etc…) from the server so not only can the processing/calculation be performed efficiently on the local machine but the server can also act in a more efficient manner by serving up coarse grained objects (more content and less overhead as requests are amalgamated).

• • • 38 • • • SECTION II INTRODUCTION 4 – Carousel, User Guide

• • • 40 • • • 5 – Installing Carousel Carousel, User Guide

5 Installing Carousel

Carousel can be installed in a number of ways depending on the intended usage. At its simplest Carousel can be downloaded and used as is. At the other end of the scale Carousel requires a number of installations to access all features.

Downloading Carousel

Carousel can be downloaded from the Xoetrope website at http://www.xoetrope.com. To download you need to register using a valid e-mail address. Once you have successfully registered you will be sent an e-mail with directions to the download site where you can download the version of Carousel that you need. As a registered user you will be able to download updates to Carousel on a regular basis as new features are added or enhanced. Typically a Carousel licence allows such downloads for a period of one year. Along with previous downloads we will allow access to a number of earlier versions of the software.

Carousel components

Carousel is a Java platform and therefore requires a recent Java development kit. You need to have a recent JDK (1.5) to run all the features, notably the NetBeans plug-ins. Otherwise, if you do not plan to use the editors you can use just about any JDK you like.

Component Usage

Carousel Carousel can be used with just about any Java development environment. All you need do to begin working with Carousel is add the carousel.jar module to your project’s classpath. To use Carousel in this way simple download the jar file and installed it somewhere that can be accessed by your development environment.

NetBeans plug-in module The Carousel editor is based on the NetBeans platform and is delivered as plug-in for the NetBeans IDE. Installation of this module is described in detail below.

Table 5-1 — Carousel modules

• • 41 • • • • 5 – Installing Carousel Carousel, User Guide

Component Usage

Eclipse plug-in module An Eclipse plug-in provides wizards for creation of projects and pages and supports editing and debugging of XUI projects.

SurveyManager This is a tool for creation and management of survey and questionnaire applications and applets. With a little imagination this module can be used for other types of questionnaires including e- learning, tests and quiz.

ProjectManager The project manager library adds a set of classes to assist in project based applications. Projects for creation of product selection, ordering, documentation and so forth can be supported by this library. The module also contains a wizard to assist in the configuration of such projects.

Table 5-1 — Carousel modules

XUI components

Carousel is an extension of the open source XUI platform. Carousel includes XUI and the KALIDEOSCOPE but it is also possible to download XUI directly from SourceForge (http:// xui.sourceforge.net). On the files area you can obtain a number of variants of the XUI platform and these are described below. The files are delivered in two variants, one containing non-debug version of the class files and the second compiled with full debug information and include all logging and diagnostic features switched on:

Component Usage

XuiCore.jar This Jar contains all the class files needed for core XUI development using the AWT widget set.

XuiCoreSwing.jar This Jar contains all the class files needed for core XUI development using the Swing widget set.

XuiOptional.jar Extensions to the core including database bindings and more.

XuiALL.jar The complete set of class files and resources including the standalone (non NetBeans editor) and support for both Swing and AWT widget sets.

xui-src-.zip The complete source code, where is the version number.

Table 5-2 — Carousel modules

The XUI Jars are compiled for a number of JDKs and accordingly have slightly different feature sets, for example only the JDK 1.5 and later versions feature the Synth Look and Feel as that feature was introduced as part of the Java platform with JDK 1.5. The fullest feature is

• • • 42 • • • Carousel, User Guide 5 – Installing Carousel

the JDK 1.5 version and the version with the least features is the JDK 1.1.8 version (which runs on virtually all JVMs). For mobile and embedded devices the above packaging may not match a platforms capabilities so you may want to compile the source code for the platform that suits your needs. All the source and the build files are available, so you can tweak the feature set to suit your needs. For example, some mobile platforms include Swing and JDBC connectivity while others don’t, depending upon the level of compatibility provided. Therefore to avoid proliforation of the number of versions compiled we have stuck to the core JDK when building pre-packaged versions of XUI. The XUI jars are not signed, since you may need to sign the jars with a single certificate to distribute via Java Web Start. Therefore you need not stick to the packaging provided by the pre-built jars. For a minimal footprint you may even want to strip down the jars so that you only include thoses classes that you absolutely need. However, please ensure that you observe the licensing requirements in this regard if you change or alter the distribution.

Installing NetBeans

Carousel includes a NetBeans plug-in for rapid development. Most of the features of Carousel are used and accessed via this plug-in and it is therefore most likely that you will also require a version of NetBeans. At the time of writing the target version of NetBeans is version 5.5. Java version 1.5 (JDK 1.5) is also required to run this version of Carousel NetBeans can be downloaded from http://www.netbeans.org. The NetBeans site also contains extensive documentation of installing and using the IDE.

• • • • 43 • • 5 – Installing Carousel Carousel, User Guide

Loading Carousel

Once Carousel has been downloaded. The NetBeans plug-in is delivered as a NetBeans module file with the .nbm extension. To load the module you must first start NetBeans. Once started go to the Update Center on the tools menu.

Figure 5-1 — The NetBeans update centre.

Then choose the ‘Install Manually Downloaded Modules (.nbm files)’ option. Select the three NetBeans modules: net-xoetrope-xui.nbm, net-xoetrope-editor.nbm

• • • 44 • • • Carousel, User Guide 5 – Installing Carousel

and Carousel.nbm. The first of these are the module for the open source XUI and KALIDEOSCOPE modules and the third is the module for Carousel’s add-on features.

Figure 5-2 — Module selection.

• • • • 45 • • 5 – Installing Carousel Carousel, User Guide

When the NetBeans module has been successfully installed the Carousel menu item will appear on the main menu.

Figure 5-3 — The Carousel menu with NetBeans and the Language Editor.

If you are just installing XUI and Kalideoscope, then you can check that the installation has succeeded by check that the New XUI Project wizard is available from the File | New | Project menu option.

Installing the samples

A number of samples are available on the Xoetrope website. The samples files are simple zip archives of complete projects. To begin working with the samples you can simple download the archive and unzip the archive and open the project using the NetBeans File | Open command. The samples provided with Carousel are listed below:

Sample Description

Hello World The classic introduction.

Navigation A simple example showing how to navigate within an application.

Translation An example showing how translations can be setup and used.

Table 5-3 — Sample applications

• • • 46 • • • Carousel, User Guide 5 – Installing Carousel

Sample Description

Counter A very basic calculator showing how to link in Java code to add custom logic to an application.

Address Forms Some simple forms showing the key concepts of data binding and validation.

Mortgages A more complete example showing how to build a working example. This example is also used as a tutorial on how to use Carousel.

Table 5-3 — Sample applications

In addition to the samples listed above the source code for the case studies included in this guide can also be downloaded. New samples are occasionally added to the website and it is probably worth checking for updates (http://www.xoetrope.com). The Xoetrope website also features numerous technical articles describing new and key features.

Installing the Eclipse plug-in

Like the NetBeans plug-in the Eclipse plug-in provides interactive editing of XUI and Carousel applications. The plug-in is easy to install, just unpack the zip archice and drop the enclosed jar into Eclipse’s plugin folder and restart the IDE. When Eclipse restarts you should see the XUI project wizard under the File | New | Other dialog. At present there is no Eclipse version of the Carousel plugin.

• • • • 47 • • 5 – Installing Carousel Carousel, User Guide

• • • 48 • • • 6 – A quick tour of the editor Carousel, User Guide

6 A quick tour of the editor

This chapter provides a quick tour of the Carousel editor within NetBeans. The main features of the editor and the main steps involved in creating an application are described. The chapter is intended only as an introduction so that you can begin exploring the features built into the editor. Later chapters will cover each of the topics in more detail.

Creating a new project

NetBeans includes a range of templates for creating various pieces of applications. The Carousel templates are unsurprisingly listed under the Carousel heading. To access the templates choose File | New from the main menu. The templates included in Carousel are as follows: • New Project: Creates a the stub of a new project • New Page: Creates a blank page within the current project

Figure 6-1 — The new project wizard.

• • 49 • • • • 6 – A quick tour of the editor Carousel, User Guide

To create a new project choose the New Project template. The template is shown below.

Figure 6-2 — The new project wizard, step2 - choose the project location.

To complete the template you must choose a directory into which the new project will be generated. To get started quickly you can just choose the default settings once you have set the target directory. For the most part the options for creation of the new project are simple.

Figure 6-3 — The new project wizard, step 3 - the project settings.

The settings page also gives options for the project name, which is the name that will be used to identify the project within NetBeans. The application title is the text that appears in the application title bar, this is also the text that some operating systems used to identify the

• • • 50 • • • Carousel, User Guide 6 – A quick tour of the editor

running application. The remaining settings affect the way the application is presented and behaves. When the application first appears it can be centred on screen or it can appear in the top left of the desktop, the ‘Center on screen’ checkbox controls this behavior. The application may also be embedded in an HTML page as an applet or it may be run as a standalone application. In either case it is possible to show the applet/application in a popup window. This window does not have the usual sizeable window border. The ‘Popup Window’ checkbox controls this option. The ‘Window Size’ section is straightforward and simply lists some standard window sizes for the new application. Optionally a Splash Screen can be include. The splash screen is simple an image that is presented as the application loads, the screen typically times out after a few seconds, or it can be dismissed with a user click. By default the first page displayed is called ‘welcome.xml’, but you can choose to display a different page at startup by entering the name of the first page. There is no need to specify the ‘.XML’ suffix as this will be assumed, if there is no Java class called by the name of the startup page. One option you should take care to set correctly is the package name. This can often be confused with a path and instead it is the Java Language package name. For anyone not familiar with package names the appendix gives a brief overview of this language feature The ‘Log level’ controls the amount of information that is displayed in the console while running the application. This applies only when running the application with debug versions of the libraries (the default in Carousel). The Frameset Configuration optionally allows you to configure your application as multiple pages within a single frame or as a single page. Sometimes a frameset is used when common elements repeat across multiple screens, say for example a navigational control panel or a banner headline.

Figure 6-4 — The new project wizard, step 4 - the frameset settings.

• • • • 51 • • 6 – A quick tour of the editor Carousel, User Guide

The project is configured with multiple files to help separate the various forms of content. The most important of these are listed in the ‘File name configuration’ page.

Figure 6-5 — The new project wizard, step 4 - the file settings.

The final page of the new project wizard provides a place to configure some add-ons for Carousel. These options are intended for more experienced users but essentially they allow you to extend the types of components, data bindings and validations that can be used in an application. The parameters are all class names. More details about these options will be given in later chapters.

Figure 6-6 — The new project wizard, step 4 - customize and complete.

• • • 52 • • • Carousel, User Guide 6 – A quick tour of the editor

Once the new project has been created the various folders and configuration files are setup. Some page stubs will also be created ready for you to start building content. If you have any doubts about the options when creating the project there is no need to worry as all the options available in the new project wizard are also available on the project page. This page is opened once the initial generation of the project is finished. Once the project is created it is shown in the Project view, which shows all the classes and packages within the project. The Files view shows all the files and resources that are used in the project. The build.xml file is listed in this view and can be used to trigger actions such as the compiling, building and testing of the application.

Figure 6-7 — The project view

• • • • 53 • • 6 – A quick tour of the editor Carousel, User Guide

A number of directories are created under the project’s main directory or folder. The directories are as follows:

Folder Usage

Pages Stores the XML page declarations.

Lang Stores the language files used for translation of the application.

Resources Holds various resources used in the project including graphics, configuration files and so on.

Src The source code for the Java classes is held in this folder. Another folder (classes) may also be created depending on the configuration. The classes folder is a temporary folder and may be deleted at any time.

Table 6-1 — Project folders

• • • 54 • • • Carousel, User Guide 6 – A quick tour of the editor

The project view

Once a new project has been created the project is automatically opened. The project editor contains much of the information that was in the New Project template and allows you change the project settings at any time during the project lifecycle.

Figure 6-8 — The project settings editors.

At the top of the project view there is a set of buttons for access to additional parts of the project configuration. The options available in these windows affect all parts of the application, such as the page size and the frameset layout. Some of the options also affect the runtime behavior by adding extensions and modifying the classpath.

Note: Pages can be opened from either the File View, but while they are visible in the Project View, they will not open and instead a message is issued requesting that you open the files from the File View instead. On non English versions of NetBeans this check will fail and you make experience problems. This is a known issue that we will attempt to fix.

Pages and resources

Creating a new page in Carousel is again achieved by choosing File|New. A template is also used to create the page, but this time all you need to do is choose a name for

• • • • 55 • • 6 – A quick tour of the editor Carousel, User Guide

the page and its location. The page should be placed in the ‘pages’ subdirectory of the project.

Figure 6-9 — The new page wizard.

Later we will see how to add rules and Java code to the page and your will learn that the page name is used as the basis for a Java file. As Java is particular about class names it is best to conform to Java’s naming conventions when choosing a page name. Thus the name should be a single word, starting with a capital letter.

• • • 56 • • • Carousel, User Guide 6 – A quick tour of the editor

The page designer

Once a new page is created it is opened for editing in the editor. Here’s an example of a simple page.

A BC

Figure 6-10 — Editing a page.

At this point it is worth noting some of the overall features of the editor.

Section Description

A On the left is a hierarchical view of the project and the filesystems used by the project. The filesystem corresponds to the Java classpath used by the project. Underneath the project folder are various folders into which the different categories of files and resources are saved. Notice the pages folder which naturally enough contains the pages belonging to the project. Below the navigator, you will find the Inspector window which shows the structure of the page being edited. Sometimes the Inspector can be useful for selecting components particularly if components overlap or obscure one another. The Inspector also provides access to features such as locking and unlcoking of the components.

Table 6-2 — Areas of the editor

• • • • 57 • • 6 – A quick tour of the editor Carousel, User Guide

Section Description

B In the centre is the editor area. The screenshot above shows the page designer. The page designer is docked in this area and other editors can be selected via a set of tabs along the top edge of the editor. As the editors are activated or deactivated they may cause other windows to appear or disappear according to the context. While the page designer is active several other windows are shown and docked into the right hand side of the main window.

C On the right hand side are three windows. The component palette, the component inspector and the styles properties window. Also visible but not active is the component properties window which shares screen space with the style properties window.

Table 6-2 — Areas of the editor

Pages can be opened on their own or within a frameset. To open a page with a frameset right click the page within the Files View and choose Open in frameset. NetBeans also provides many features that will be of use to you as a developer from time to time. For example the Runtime view (not shown above, but accessible from the Window menu) provides access to runtime resources such as databases and servers. Using this view you can for instance drag a database table to a component on your page to establish a data binding, but we will cover this in more detail later in this manual.

Components

At the top right of the editor, when the page designer is active you will see the component palette. The content of the component palette will depend on the type of application being developed and whether or not any extensions have been added to Carousel. As a minimum there will be several core components shown. These are:

Icon Component description

A button object, usually used to initiate some event or action.

A check box, indicating an option selectable by the user. Where options are mutually exclusive a set of radio buttons should be used.

A drop down list or combo box, representing a list of choices. A drop down list is usually used where there is a small number of options or where the number of options is too great for a set of radio buttons.

An edit field, an input field where the user can enter a simple value. An edit field is a key input mechanism and Carousel provides support for validation of input data using edit fields.

Table 6-3 — Component palette icons

• • • 58 • • • Carousel, User Guide 6 – A quick tour of the editor

Icon Component description

An image component. Used to display images stored in the resources folder. Can be used with a MouseHandler to interact with the user.

A hotspot, a clickable area that can be placed over another object so that when the user click on the hotspot some action occurs.

An imagemap, like a hotspot except that an irregular/polygonal area can be specified as the clickable area. Like a hotspot the user can click to invoke an action.

A Label, a simple piece of text. The label text does not normally cause any interaction with the user

A Panel, a container into which other components can be placed. The panel can optionally be made to display a frame or border.

A password edit field, a special case of an edit field used for entering a password. As the user types the value of the password the field displays a mask character for each letter or character typed.

A scroll panel, a special form of a panel that supports scrolling. The pane can optionally be scrolled horizontally or vertically. The scroll pane automatically adjusts itself to the size of its content.

A table, a simple table component that can display data directly from the model. Headers and alternate row shading are just two of many features that the table control supports.

A text field, a simple text field. This component supports multiple lines of text.

Table 6-3 — Component palette icons

The user can add any of these components to the page by first selecting a component from the component palette and then placing it by clicking at the desired location on the page. Components can be nested by placing panels on the page and then placing additional components on the new panel. The panel is then considered to own the new components or children. When the panel is moved so too are the children. As each component is selected the properties of that component are displayed in the properties palette, the style palette and the component inspector. Properties can be changed by choosing options within the properties palettes or by double clicking on styles. The component inspector is primarily a mechanism for showing the hierarchical relationship between components. Multiple components can be inspected at once but only the common subset of the properties will be available in the various palettes and you may not always be able to interact with all properties. When fully configured Carousel may include several sets of components or widgets. The components belonging to these widget sets are displayed on separate tabs within the component palette. The availability of some of these widget sets may depend on the project

• • • • 59 • • 6 – A quick tour of the editor Carousel, User Guide

configuration, for example if an AWT application has been chosen then the Swing widgets will not be available.

Styles

Styles in Carousel comprise sets of colors and fonts that can be applied to just about any component. The style palette provides a simple way to interact with the styles, by simply selecting a component and double clicking a style value.

Figure 6-11 — The style chooser.

Styles can also be changed by simply changing the style file or by changing individual styles (by right clicking on the style palette). Carousel even includes a color scheme picker (which again can be accessed by right clicking on the style palette). The color scheme picker is designed to allow you to quickly choose and experiment with styles that will produce a visually attractive application.

Source code

An application generally isn’t a lot of use unless it can do something. Carousel is designed to make it easy to build applications and therefore adding custom functionality and business logic is simple. When you select a component you will see its properties in the property sheet. Depending upon the component type this property sheet may display some event properties. For example a push button will have an ActionHandler property. By typing in the name of the source code method you can edit the Java source code for that method, and if no such method exists the stub of a new method of that name will be inserted into you Java source code file. Later we will see how such an event handler is actually connected up to the user interface. However it is worth noting that Carousel declares such links in the page’s XML. You can

• • • 60 • • • Carousel, User Guide 6 – A quick tour of the editor

switch back and forth to this XML by clicking the (Design and XML) buttons at the top of the page designer. Of course you can also find the Java code in the Files view and open the file directly. The file is just a normal Java file and there are no hidden or special sections to worry about. For example to add a piece of application logic simple choose the component that will

Figure 6-12 — The XML edit for a page. initiate the action and within the properties palette find the appropriate response and just enter the name of the response method. Upon pressing Enter the source editor is opened and you can edit the Java code belonging to the event. At any stage you can switch back to the page designer by clicking on the tabs above the source editor or by closing the source editor. The pageDesigner also allows you to selecting existing functions and attach then to a component. A list of available functions is displayed in the drop when you click on the event handler in the proeprty sheet, so if you do not want to enter the name of new event just choose Hold the CTRL key one of the predefined functions if appropriate. Once you have added a function and wish to jump while you click on an to the source code, just hold the CTRL key while you click on the event handler and this will open existing event handler the source code editor instead of editing the to open the source code handler name. In later chapters we will see just how to begin editor coding custom business logic.

• • • • 61 • • 6 – A quick tour of the editor Carousel, User Guide

XML

As a technology both the KALIDEOSCOPE and Carousel make extensive use of XML. XML is used to describe a wide variety of things in Carousel, including the user interface. The XML for a UI can be displayed by choosing the XML tab for that page. Furthermore Carousel allows two-way editing of the XML whereby any edits to the XML will be reflected in the page and any changes to the page within the page designer will be displayed in the XML. The updates occur as the display is modified by choosing the tabs along the top of the editor. Later chapters will explain Carousel’s use of XML in greater depth.

Compilation

Writing code for an application is the first step in making working code. Java is a compiled language and therefore the source code needs to be compiled. The quickest and easiest way to do this is to right click on the project node in the XUI view. The context menu then shows a compile all option and choosing the Compile or Execute option will compile all classes within the project. NetBeans also includes many options to control compilation, building and testing of an application and you should refer to the NetBeans documentation for more information on the available options.

Testing

Once the project has been successfully compiled you should test it prior to distribution. Carousel and the underlying NetBeans platform provide a powerful testing and debugging environment. To test an application simply choose the Debug Project option from the popup menu on the tree icon for the project in build.xml file in the Files View.

Deployment

Finally to make widespread use of your application you need to package and deploy the application. There are wide variety of deployment scenarios and these will be covered in detail in later chapters. Again NetBeans provides additional plug-ins to help manage the deployment of application, including Java Web Start deployments, and you may wish to download some of these extra plug-ins. Carousel generates a stub of a JNLP file that can be used by such plug-ins.

• • • 62 • • • 7 – Running applications Carousel, User Guide

7 Running applications

Within Carousel starting an application is handled by NetBeans using the normal Run or Debug commands. Outside of NetBeans several methods can be used to start-up Carousel applications depending upon how the applications will be deployed. All of these start-up sequences start by invoking the XApplet class and eventually follow a generic initialization process. Some minor variations are accommodated by the XApplet class to handle the different ways of setting start-up parameters and the differences in the classloaders. When starting a Carousel application the choice of the XApplet class is important as this dictates whether or not the Carousel framework constructs Swing or AWT components. If the net.xoetrope.awt.XApplet class is used then AWT components are used, whereas if the net.xoetrope.swing.XApplet version is used Swing components are constructed. In the examples above it will be assumed that AWT is being used, but the examples will work just as well with Swing if the Swing version of XApplet is substituted. For the purposes of simplicity it will be assumed in the following discussions and examples that Java is installed as default and that Java can be started without additional modification of the environment or path.

Command-line startup sequence for applications

To start an application from the command line it is only necessary to invoke the XApplet class.

java -cp XuiCore.jar net.xoetrope.awt.XApplet startup.properties

Code Sample 7-1 — Command Line startup command

where startup.properties is the name of the initialization file (which if omitted will default to startup.properties). The application can take one additional parameter, the default package name. Make sure to use the -cp or -classpath switch instead of the - jar switch (unless yo build a custom self-starting jar). The default package name for an application is normally set by whichever version of the XApplet is used to start the application (net.xoetrope.awt for the net.xoetrope.awt.AXpplet class and net.xoetrope.swing for the net.xoetrope.swing.XApplet class). It is very rare that this parameter would need to be set as the application will automatically set the appropriate default value. Note that the startup file is generated by Carousel each time the project is built, however Carousel actually stores the values is the project.xui file for its own use.

• • 63 • • • • 7 – Running applications Carousel, User Guide

Java Web Start Start-up Sequence

To run a Carousel application as a Java Web Start application several preparatory steps are required. Firstly, the application must be packaged as an appropriate set of Jar files. Next the application Jar files and resources must be signed and placed on a server configured to serve JNLP files. In particular, pay attention to how the mime-type is set for your particular server. In some cases the mime-type can be set by using dynamic content on the server such as JSPs or ASPs instead of vanilla HTML. Once the Jars files are on the server the JNLP file can be configured. Here's an example:

Carousel 1.0 My Company

Code Sample 7-2 — Java Web Start (JNLP) startup code

To actually launch the Web Start Application it is then just a question of invoking the JNLP file. Normally this is done by embedding the link in an HTML page. Normally it is also the practice to check that JWS is installed and display an appropriate error message if it is not. Sun's JWS web pages give examples and documentation of how to do this.

HTML/Applet Start-up Sequence

The HTML initialization sequence is like the JNLP in some ways except of course that it is an applet that is being started and not an application. Security settings are also different for applets depending on the environment in which they run. The HTML fragment required for an applet if as follows:

Code Sample 7-3 — Basic applet tag

Again the Jar file should be signed for distribution and placed on the webserver.

• • • 64 • • • Carousel, User Guide 7 – Running applications

Generic Initialization

Once the XApplet class has been invoked the initialization of the application/applet is pretty much the same regardless of how it was started. The sequence (and purpose of each step) is as follows: 1. Register the component factories. The registration process involves reading the 'NumComponentFactories' parameter from the start-up file and then reading, instantiating and registering the number of component factories listed in the start-up file. Implicitly either an AWT or Swing component factory is already registered 2. Setup the project class. The project class maintains references to all the other resources, managers and factories used by the application. The project manager class can be accessed through a static accessor method and with this mechanism any resource can be easily obtained from the project without the need to carry references to the various objects. 3. Setup the page manager. The page manager controls the application display areas and acts as a broker for displaying frames and pages. The page manager also provides some navigation and page history support. At this point the content is also setup by specifying a frameset (if any) with the 'Frames' parameter and the content with the 'StartClass' parameter. 4. Setup the resource access. The resource access provides a simple method of loading resources and hides details of the various classloaders, paths and so on. Resource access is managed by the XProject instance which does some caching of resources such as images that are frequently reused. 5. Setup the style manager. This class loads style information from a file indicated by the 'styleFile' parameter in the start-up file. Styles can be used to configure fonts and colors in a consistent manner. 6. Size the main window. The startup parameters 'ClientWidth' and 'ClientHeight' are used to set the size of the main application window. The main window (in the case of an application) can also be centred by setting the start-up property 'CenterWin' to true. 7. Set the layout. Assuming that some content was configured the application/applet is now laid out. This process will position the various elements of a frameset and the content of the frames or the content of the main window if no frameset is being used. 8. Add a shutdown hook. A shutdown hook is largely used for debug purposes to allow output of logging information. Shutdown hooks were not available on earlier JDKs so this feature may not be in use on all environments (particularly embedded platforms) 9. Display the main window. The application is now ready to display and the main window is shown. If you need to display a splash screen one good place to initiate its display (without subclassing XApplet) is when the first page is created, by embedding code in that page's pageCreated or pageActivated method. Carousel 3.0 refactored must of the startup infrastructure so that there is very little need to know any of the above detail, even if you are building a custom setup or a custom application type. Carousel provides several stubs for the propular widgets sets and the normal application styles, however should you need something other than this then you can implement your own startup process quite easily as most of the necessary functionality is encapsulated in the XApplicationContext class which is used to setup the common infrastructure by the XUI framework. An example of this is the sample application that

• • • • 65 • • 7 – Running applications Carousel, User Guide

integrates XUI into the run-of-the-mill Swing application as a panel embedded in that application (see “Embedded applications” on page 198).

Startup file stubs

Carousel creates a number stubs of the startup file whenever a project is generated. These files are found in the root directory of the project and are regenerated each time the project is generated.

Eclipse Debugging

In Eclipse the process of debugging is somewhat different to the NetBeans Experience. To debug the project simply right click the project in the Navigator or Package Explorer and choose the Debug As option and select Java Application. Before Eclipse can run the application it needs to know the main entry point into the application, and to find this it will pop up a dialog requesting that you select the main class.

Figure 7-1 — Choose the main class.

The XUI libraries should be on the project classpath and therefore Eclipse should be able to locate the XApplet class as shown above. Note that for other application styles you may need to specify additional startup parameters and in this case you will need to create a custom debug configuration - see the Eclipse documentation for more details on doing so.

• • • 66 • • • 8 – Getting started Carousel, User Guide

8 Getting started

In this chapter we will see how to build some simple Carousel applications using both Java and XML. We will see all the features needed to build a fully functional application within Carousel in action. The chapter provides an introduction to the setup mechanisms used within a Carousel application. Most of the features described can be configured interactively but to aid understanding they are explained at a lower level. The chapter assumes that you have already encountered the features described in the previous chapter and that you have a basic understanding of how Java based applications function. Don’t worry if you do not understand all the nuances of the technology described as the various pieces of the application are but together. Later chapters are devoted to the individual features employed. If you are new to Java we recommend that you study some of the numerous educational resources available on the Internet, some of which are listed in the appendix on Java (“Learning Java” on page 490).

Hello world

Traditionally the first example used in many user guides is the infamous 'Hello World' example where the task is to emit or display the simple text 'Hello World'. In Carousel this is very simple, all you need do is create an XML file called 'home.xml', preferably in a new folder. The XML file contains the declaration of the user interface needed for this task. It looks like the following:

Code Sample 8-1 — Page user-interface declaration

And that's just about it. The only other thing that is needed is a convenient way of starting the application. To do this we create a startup command file. This command file doesn't have to do very much other than invoking the Java environment and telling it what class to start. The

• • 67 • • • • 8 – Getting started Carousel, User Guide

start class in this case is the entry point to the Carousel framework or library. It contains the following command:

java -classpath .;XuiCore118.jar; net.xoetrope.awt.XApplet

Code Sample 8-2 — Command-line startup

The XuiCore118 jar is the minimum level of library support that can be used with Carousel. It is a version of the Carousel core compiled for early JDKs (including the Java environment embedded in Microsoft's Internet Explorer). To use a fuller more functional JDK, for example to access the Swing toolkit instead of the AWT simply change the startup file to use this command:

java -classpath .;XuiCoreSwing.jar; net.xoetrope.swing.XApplet

Code Sample 8-3 — Command-line startup for Swing

Running this command will create a Swing user interface (UI) for the application. The two versions of the application should look pretty much the same. This little example immediately shows a number of the benefits of Carousel and XML. Most obviously the UI declaration is very small and compact. Consider all the code needed to get such an example up and running in many languages. Secondly the approach of separating the UI declaration from the implementation makes it easy to switch that implementation, as shown above in switching from the AWT to Swing toolkits.

Hello world redux

Another much touted benefit of Carousel is its close integration with Java and the ability to declare the UI in XML or in Java. To emphasize this let's see how we can build the same thing in Java. This time instead of creating 'home.xml' we need to create a Java class. Using the normal naming conventions and capitalization we will call this class 'Home.java'. The Java code needed is as follows:

import net.xoetrope.xui.*; import net.xoetrope.awt.*;

public class Home extends XPage { public Home() { addComponent( XPage.LABEL, 32, 37, 100, 29, "Hello World" ); } }

Code Sample 8-4 — Java UI class

Now while this isn't as compact as the XML declaration it is nonetheless a little more compact than the traditional Java code used for such an example.

• • • 68 • • • Carousel, User Guide 8 – Getting started

To run this example there is of course another step required, that is, to compile the Java code. This can be done from the command-line, in the root directory of the project. Just type the following command:

javac Home.java

Code Sample 8-5 — Command-line startup for compilation of the Java class

This should create a file called 'Home.class' in the same directory. The application can then be run in the very same way as the XML version. The underlying XUI will try loading an an XML file in preference to a Java class, so if it finds your XML file first then that will be used instead of the Java class even if the two files are in the same folder.

Beyond HelloWorld

While the HelloWorld examples offer a minimal way of getting started with Carousel it is not normal. Carousel can use many different resources and settings to configure and run an application. The HelloWorld examples relied on default settings for most of the Carousel configuration. Normally Carousel applications are configured via a startup properties file. This file can be specified as a command-line argument:

java -classpath .;XuiCore118.jar; net.xoetrope.awt.XApplet startup.properties

Code Sample 8-6 — Command-line startup using a startup properties file

Or, if no command-line argument is provided Carousel will look for 'startup.properties'. (And remember that the startup file is regenerated by Carousel whenever an application is saved. Carousel itself uses a file project.xui to store the properties that are written to the startup.properties file). It is also useful to separate the various components of an Carousel project into separate sub- Carousel uses a file directories. Thus the XML declarations for pages are put into the 'pages' sub-directory, while the ‘project.xui’ to store the Java source files are places in the 'src' sub- directory. Other resources such as images are properties that are placed in the 'resources' sub-directory and written to the finally localization files are placed in the 'lang' subdirectory. ‘startup.properties’ file. When using Carousel (as we will see in the next chapter), a special class/resource loader is built-in and can locate files in these subdirectories without the need for them to appear on the classpath.

• • • • 69 • • 8 – Getting started Carousel, User Guide

The startup file contains settings that control much of how Carousel is configured. Some of the more commonly used configuration settings are shown below and could be used for the HelloWorld example.

CenterWin=true ClientHeight=480 ClientWidth=640 StartClass=Home Title=A simple HelloWorld example StyleFile=styles.xml UseWindow=true StartPackage=xui.projects.helloworld

Code Sample 8-7 — Startup properties

The purpose of these settings is as follows:

Startup parameter Usage

CentreWin (true|false) Centers the application window on the screen when set to true.

ClientHeight Set the height of the application window in pixels.

ClientWidth Set the width of the application window in pixels.

StartClass Sets the name of name of the initial class or XML file to display.

StartPackage Sets the name of the package used for this application's Java classes. In the case of the HelloWorld examples no package was used so this setting could be omitted. The above example indicates that Carousel should look for a class called 'xui.projects.helloworld.Home.class'.

UseWindow (true|false) Tells Carousel to use a Window without a border or use a normal application frame to hold the application.

StyleFile Points to the name of a style file used to configure the colours and fonts in the application.

Table 8-1 — Startup parameters

Building a simple address form

Most applications require user interaction and some data capture. Typical of this is entry of user details including name, telephone numbers and addresses. This example goes beyond what was used in HelloWorld and shows some of the major steps in creating an attractive UI. We will start by creating a very simple form and then we will apply some style information to improve the look. In later sections this example will be expanded to produce a fully working, full featured form.

• • • 70 • • • Carousel, User Guide 8 – Getting started

To start with we need a declaration of the input fields needed to capture the user input. We will use XML for this, and at its simplest this looks like the following:

Code Sample 8-8 — An address form/page declared in XML

In the above declaration the Label fields are all right aligned and the edit fields are all named. We name the edit fields as later we will want to interact with them programmatically. This form is basic and does not include any formatting specific to any region. The address is comprised of three lines whereas most applications would further customize addresses for things like post or zip codes. We leave such customization as a user exercise as it will not affect the overall behavior of the form. Note also that the form is laid out using absolute positioning and that in general it is better to use layout managers for the positioning of components (again, this will be covered in later chapters). Generally the order in which the components are declared is of little importance, but it is in this order that the components are added to the container and therefore this dictates the z- order of the components. The z-order may be of interest if components overlap.

Applying style

To improve the appearance of the form we apply some styling information. This style information simply consists of the name of a style to use when rendering the component. Carousel includes a style editor for interactively setting up the colours and fonts that comprise styles. These styles can then be interactively applied to a component or alternatively the styles can be applied via the Java code as the application executes.

• • • • 71 • • 8 – Getting started Carousel, User Guide

The style details are stored in an XML file pointed to by the startup parameter 'StyleFile'. In the absence of a file name the files 'styles.xml' is used. A typical style file includes colour and font information as below:

Code Sample 13-3 — Using SystemColors

The system colors are dependant on the user preferences and may vary from user to user and machine to machine. The system color properties are:

Name Usage

desktop The color rendered for the background of the desktop.

activeCaption The color rendered for the window-title background of the currently active window.

activeCaptionText he color rendered for the window-title text of the currently active window.

activeCaptionBorder The color rendered for the border around the currently active window.

inactiveCaption The color rendered for the window-title background of inactive windows.

inactiveCaptionText The color rendered for the window-title text of inactive windows.

inactiveCaptionBorder The color rendered for the border around inactive windows.

window The color rendered for the background of interior regions inside windows.

windowBorder The color rendered for the border around interior regions inside windows.

windowText The color rendered for text of interior regions inside windows.

menu The color rendered for the background of menus.

menuText The color rendered for the text of menus.

text The color rendered for the background of text control objects, such as textfields and comboboxes.

textText The color rendered for the text of text control objects, such as textfields and comboboxes

textHighlight The color rendered for the background of selected items, such as in menus, comboboxes, and text.

Table 13-1 — System Colors

• • • • 133 • • 13 – Styles Carousel, User Guide

Name Usage

textHighlightText The color rendered for the text of selected items, such as in menus, comboboxes, and text.

textInactiveText The color rendered for the text of inactive items, such as in menus.

control The color rendered for the background of control panels and control objects, such as pushbuttons.

controlText The color rendered for the text of control panels and control objects, such as pushbuttons.

controlHighlight The color rendered for light areas of 3D control objects, such as pushbuttons. This color is typically derived from the control background color to provide a 3D effect.

controlLtHighlight The color rendered for highlight areas of 3D control objects, such as pushbuttons. This color is typically derived from the control background color to provide a 3D effect.

controlShadow The color rendered for shadow areas of 3D control objects, such as pushbuttons. This color is typically derived from the control background color to provide a 3D effect.

controlDkShadow The color rendered for dark shadow areas on 3D control objects, such as pushbuttons. This color is typically derived from the control background color to provide a 3D effect.

scrollbar The color rendered for the background of scrollbars.

info The color rendered for the background of tooltips or spot help.

infoText The color rendered for the text of tooltips or spot help.

Table 13-1 — System Colors

Extended Styles Styles can be extended to add attributes other than the basic color and font attributes. However the use of these extra attributes is dependant upon the context such as the component or class using the style. The extra attributes are automatically added for the style when the style is loaded. Once the stle has been loaded it is marked as closed and any attempt to access an unrecognised style name will cause an error (this can be changed with the XStyleEx.setClosed(...) method). An example usage of the extended styles is the validation style, which uses three

• • • 134 • • • Carousel, User Guide 13 – Styles

colors to specify the feedback colors for the validation states. The validations styles could thus be specified as:

Code Sample 13-4 — Specifying extended styles

Note the extended attribute for the style. By adding extra style attributes you may be able to provide additional consistency within the application as attributes for various classes can be specified on an application wide basis instead of via a class by class or component by component basis. In many cases you can specify the attribute values for components, for example alignments and borders. In applying a style the framework will attempt to set component attributes using the style name and value via either the XAttributedComponent interface or via Reflection. The basic types such as String, int, double, float and boolean values can be accomodated. The built-in styles are handled directly as described above and set the component’s colors and font.

...

Code Sample 13-5 — Setting right aligned label styles and properties

• • • • 135 • • 13 – Styles Carousel, User Guide

Applying styles

To apply a style to a component you just need to reference the style in the page's XML declaration. Thus applying style to an address form becomes:

Code Sample 13-6 — Style usage

Related issues

Colors and fonts are not the only style related things that should be consistent within an application. Layouts, naming, data representations, translations and so on should also be consistent. Consistency will make it easier for a user to grasp the concepts behind the application and it will make it easier to understand the mechanism used within the application for various tasks. Logically grouping elements can also assist readability. So, for example placing related components together within a framed panel gives a visual clue as to the association of those components. Subtle shading of panels can also assist in giving the necessary visual clues about the role of an individual panel particularly if the coloring is reinforced by the behavior you code into the applications. Layout In terms or readability it is often said that the average person can optimally perceive about seven pieces of information. In an application it is often difficult to limit the number of items or components displayed at once. Therefore style can play an important role in reducing apparent clutter and confusion. The style manager can go along way to helping produce a harmonious color scheme and if judiciously employed such a scheme may allow you make better use of the on-screen space. To maximize such benefit it is important that your layout is consistent. Careful consideration should be given to alignments, spacing and grouping of components. All of these features can greatly assist in the smooth flow of action within an application. A later chapter (“Layout” on page 143) details how layouts can be controlled within an application. With dynamic content it is always important to consider how the content will appear. Carousel makes it easy to dynamically modify the content of a component but this generally

• • • 136 • • • Carousel, User Guide 13 – Styles

doesn’t mean that the layout of that component will be modified. Particularly for elements that display text it is important to note the interaction of fonts and layouts. Some fonts are narrower than others or have different distributions of character widths and therefore it is important to test your application with a representative set of data. Flow Just as layout is important, the flow of text and components can have a major impact on the user experience. Generally it is best to keep it simple: left, right, top to bottom. Keep it simple, reinforce the visual signals, update consistently. Naming Styles should be named consistently for two reasons. Firstly from a programming point of view a consistent naming convention will make reading of code easier and hence development and maintenance will be easier. We recommend that you use a convention similar to the naming convention you would use in programming Java. Secondly a consistent style naming convention is important where styles are being modified and particularly where the Color Chooser is being used. The chooser can modify existing styles depending on the style name and therefore a consistent naming convention will help avoid confusion when styles are modified in this way. Data/formatting Some values such as numeric, date or monetary values may be formatted specially and styles can be used to reinforce or highlight important values such as negative monetary values.

Setting the system look and feel

The system look and feel can be set up using a look and feel (LAF) installer. The LAF installer is controlled by a startup parameter “LAF”. The value of this parameter refers to a helper class that installs the LAF and takes care of the initialization. This setting is only appropriate for Swing applications as changing the LAF is not supported in the AWT. Setting the Look and Feel In Swing you can alter the look and feel of an application by setting the 'Look and Feel' manager for the application. The look and feel (LAF) affects the visual appearance of components and some of the soft behavioral attributes, like highlighting, rounding of button edges and so on. The LAF may also have a broader impact by changing indentations, component sizes and layout. Setting the LAF is fairly straightforward within Carousel. The project settings pages include the option to choose the LAF. (it is on the files page as somewhat tenuously you need to choose a configuration file for the synth LAF) Adding a new LAF is also possible and Carousel makes this even easier than normal by allowing you to simply plug-in the look and feel via a startup parameter. Carousel comes with support for a few popular LAFs, but it is also easy to add support for your favorite LAF. The component class for setting the LAF is part of the Open Source XUI and hence you can

• • • • 137 • • 13 – Styles Carousel, User Guide

review the source code for the LAF installer to see how to build an installer for some other LAF. The LAF is set with the following startup parameter

LAF=net.xoetrope.optional.laf.SynthInstaller

Table 13-2 — Setting the look and feel

This setting refers to a helper class that installs the LAF and takes care of any initialization that is necessary. Carousel lists a few popular LAFs, including the default LAF, JGoodies Looks LAF, Windows and the Synth LAF. Of these, the Synth LAF is probably the most interesting as it is configured via XML. Configuring Synth The Synth LAF requires a number of extra parameters to be configured to operate correctly.

SynthConfigFile=demo.xml SynthResourceLoader=mypackage.MyClass

Table 13-3 — Synth parameters in the start-up file

These parameters may vary significantly depending on the content of the Synth configuration file. The SynthResourceLoader is the name of a class that will be used to load the resources used by the Synth LAF. The class does not need to do anything special as it merely provides a (classloader) route to the resources. When the Synth LAF is chosen a number of new styles are added to the project if they do not already exist. These styles are used by the LAF and you can customize them to alter the look. Note that the Synth LAF provides rendering for many aspects of the components and the LAF may therefore override the styles you have chosen for individual components. Some of the built-in components have an option to suppress the LAF and use the styles you explicitly apply to the component. SkinBuilder A sample project ‘SkinBuilder’ is included in XUI 3.0, this application is another demo of XUI, but it can be used to configure the Synth Look and Feel, including choosing artwork, setting properties and colorizing the LAF . See the accompanying documentation for more details. Using styles with Synth While the Synth look and feel can be used out of the box it is often desirable to connect the look and feel to the application’s styles for added consistency. The Synth look and feel is configured via an XML file and this configuration file can itself be preprocessed to include colors and fonts from the applications look and feel. Some special expressions can be embedded in the XML and when processed these are converted into the color and font declarations expected by Synth. Scalable Vector Graphics (SVG) images can also be used with Synth by way of the preprocessor. Carousel can convert a referenced SVG into a PNG raster graphic for use in the

• • • 138 • • • Carousel, User Guide 13 – Styles

final application. Using SVG in this way allows you to create sophisticated icons and buttons for your application and have these images scale to the required size.

Expression Example Result Usage

${getFontFace(styleName)} Arial Gets the font face name from the style

${getFontSize(styleName)} 10 Get the font point size from the style

${getColorBackground(styleName)} F0C2E9 Get the foreground color from the style

${getColorForeground(styleName)} F00000 Get the background color from the style

${getFontWeight(styleName)} BOLD Get the font weight from the style

${getFontItalic(styleName)} ITALIC Get the font italic flag from the style

${svgToPng(styleName)} images/ Convert an SVG image to a PNG. Optional width button.png and height attributes can also be specified after the source image name. If they are omitted a 50x50 image is created. A PNG image sometimes includes an optional preview of the image.

${svgToTiff(styleName)} images/ Convert an SVG image to a TIFF. Optional width button.tif and height attributes can also be specified after the source image name. If they are omitted a 50x50 image is created.

Table 13-4 — Synth substitution expression

Using SVG and Synth Just as the Synth file can be processed so to can the preprocessed SVG files. SVG uses a slightly different definition of colors so different expressions are required but the concepts are the same. The substitution expressions also come in a number of variations to help support generation of gradients from a single style.

Expression Example Result Usage

${getColorForegroundRgb(styleName)} rgb(108,128,255) Gets the RGB foreground color from the style

${getColorForegroundHex(styleName)} F0C2E9 Gets the HEX foreground color from the style

${getColorBackgroundRgb(styleName)} rgb(108,128,255) Gets the RGB background color from the style

${getColorBackgroundHex(styleName)} F00000 Gets the HEX backgroundcolor from the style

Table 13-5 — SVG substitution expression

• • • • 139 • • 13 – Styles Carousel, User Guide

Expression Example Result Usage

${getHsbColorForegroundRgb(styleName)} rgb(108,128,255) Gets the RGB foreground color from the style

${getHsbColorForegroundHex(styleName)} F0C2E9 Gets the HEX foreground color from the style

${getHsbColorBackgroundRgb(styleName)} rgb(108,128,255) Gets the RGB background color from the style

${getHsbColorBackgroundHex(styleName)} F0C2E9 Gets the HEX background color from the style

Table 13-5 — SVG substitution expression

Each expression in the table above can have just a style name as an argument or it can have the style name plus percentage values for each color channel. Thus an expression such as getColorForegroundRgb(HeadlineStyle,50,60,80) obtains the color from the style, splits out the RGB color channels and returns a color that scales the channel values by the percentages given. So if the red value was 240 the example expression would return a color with a red value of 50% or 120. Similarly if the percentage given is between 100% and 200% the color value is scaled up to 255. In this way a red value of 120 and a percentage of 150 would result in a color with a red value of 187 (i.e. 120 + (255-120)*50/100). The expression set also includes a variation where instead of scaling the RGB values the HSB values are scaled. In some cases it may be easier to specify the gradient color stops as variations in saturation or brightness values. The scaling of the HSB values works in the same way as the RGB values. Carousel automatically adds a set of styles for Synth when you select the Synth LAF. These styles are the styles that are used in the preconfigured Synth LAF that is part of XUI. However you can further customize the look and feel to use whatever graphics files and styles that you like, the configuration file is just another XML file that you can edit. To add another style to the Synth LAF just add the matching style within Carousel or within the style file. Then embed the relevant expression from the list above in your Synth configuration file. The Synth LAF requires the Batik SVG engine to process SVG images. The libraries for Batik must be part of your project for this process to work correctly. More information on Batik can be found on the Batik website. Panel backgrounds Synth can be used to paint many components including the panel backgrounds but in some cases a different look or style is desirable for painting panels to help distinguish part of an application. A custom painter class can be used for such painting, the code for configuring such a background painter is shown below:

Table 13-6 — Setting a background painter

• • • 140 • • • Carousel, User Guide 13 – Styles

The example below shows a number of panels using this custom painter to display a gradient background with a watermark logo.

Figure 13-5 — Custom panels and the Synth Look and Feel.

Painters XUI 2.0 introduced the notion of painters much like the painters used within the Synth look and feel, and since then the use of painters has become more widespread. XUI 3.0 adopts the SwingLabs painter API in an effort to conform to standards and to make a wider range of painters available. The painters API is straightforward.

public void paint( Graphics2D g2d, JComponent comp, int w, int h );

Table 13-7 — The painters API

and can be used in a varient of XUI and Carousel components. The painter is normally responsible for painting the entire client area of the component, but of course it is open to configuration. The painter class need not extend a component and therefore it acts purely as helper class. Some painters included in Carousel are:

Painter Appearance/Role

BandPainter Fills the client area with a number of coloured bands, graduating from the foreground colour to the background colour.

FlarePainter Fills the client area with a radial gradient using the foreground and background colours

Table 13-8 —

• • • • 141 • • 13 – Styles Carousel, User Guide

Painter Appearance/Role XTitlePainter Extends the XGradientBackground by adding a caption XGradientBackground Fills the background with a gradient. The gradient uses the background and foreground colours. The painter can be configured to ‘nest’ its gradient into the parent coordinate space so that multiple panels appear to share the same gradient.

XSvgPainter A painter based on an SVG images. See the section SVG Support for more details. The painter can interact with the mouse for various effects.

XImagePainter Paints an image in the client area.

Table 13-8 —

Style guidelines

A full discussion of styles is beyond the scope of this guide, however a number of style guidelines have been published and depending on your target platform and personal tastes it may be worth consulting these guidelines for clues as to best practice.

Java Look and Feel Design Guidelines: http://java.sun.com/products/jlf/

Introduction to the Apple Human Interface Guidelines: http://developer.apple.com/documentation/UserExperience/Conceptual/ OSXHIGuidelines/

Official Guidelines for User Interface Developers and Designers: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnwue/html/welcome.asp

Palm OS User Interface Guidelines: www.palmos.com/dev/support/docs/uiguidelines.pdf

SwingLabs Painter http://javadesktop.org/swinglabs/build/weekly/latest/swingx-HEAD/javadoc/org/jdesktop/ swingx/painter/package-summary.html

Table 13-9 — Look and feel resources

• • • 142 • • • 14 – Layout Carousel, User Guide

14 Layout

By default Carousel uses absolute positioning of components, with each component having explicitly specified size and location. Frequently it is more convenient to use some of the additional layout facilities found in Carousel and in Java to both improve the overall appearance and simplify development. Carousel even provides its own layout manager to support interactive visual layout above and beyond what is possible with explicit layout while providing the runtime resize and position behavior that are frequently hard to achieve with other layout managers.

Default layout

As mentioned in the introduction Carousel assumes that each component’s coordinates are specified explicitly. Simply speaking this means that each component must have a specified X, Y location and a width and size dimension. The dimensions are all in pixels and do not vary with the size of the application window or the page container. Limitations of explicit layout Perhaps the greatest limitation of explicit layout is that the pages do not resize with changes to the application window and therefore if the application is made full screen it does not make good use of the available screen space. Another significant limitation of the explicit layout is that it is not always possible to know the size needed for a component or a component’s content in advance. Dynamic sizing of components can alleviate such problems. Later in this chapter we will see how Java’s Layout Manager facility has been adapted to help address some of the issues. Carousel provides a number of tools to support interactive positioning of controls. The tools include grids and guides. These tools can be used with several of the supported layout managers but work best with Carousel’s own layout managers; the GuideLayout and the ScaleLayout.

• • 143 • • • • 14 – Layout Carousel, User Guide

Alignment tools

Carousel provides several tools for aligning components within a container and even spanning containers. These tools are located on the toolbar within the page designer and perform the following functions:

Title Usage

Align Bottom - aligns the bottom edges of all the selected components. The components are moved and retain their current height.

Align Centre - aligns the centres of all the selected components. The components are moved and retain their current width.

Align Left - aligns the left edges of all the selected components. The components are moved and retain their current width.

Align Right - aligns the right edges of all the selected components. The components are moved and retain their current width.

Align Top - aligns the top edges of all the selected components. The components are moved and retain their current height.

Justify Horizontal - aligns the left and right edges of all the selected components. The components sized according to the minimum left and maximum right hand coordinates.

Justify Vertical - aligns the top and bottom edges of all the selected components. The components sized according to the minimum top and maximum bottom coordinates

Space Vertical - Adjusts the space between the selected components so that the space is equal distributed along the vertical axis

Space Horizontal - Adjusts the space between the selected components so that the space is equal distributed alongthe horizontal axis

Table 14-1 — Alignment and Justification Tools

The alignment and justification tools are primarily designed to work with explicit layouts and will adjust the coordinates of the selected components. Use of the alignment tools with pages controlled by layout managers can lead to results that vary according to the specific layout manager and its current settings.

Grids and Guides

In the page designer the page being edited can be shown within a grid and with layout guides. The designer shows rulers to the top and left of the page, set out in pixel units. The designer allows components to optionally snap to the grid. The selection of this option and the granularity of the grid can be configured within the page designer. In the top left

• • • 144 • • • Carousel, User Guide 14 – Layout

hand corner or the designer is a button, that when pressed toggles the display mode. When in the configuration mode the rulers are shown with a red tint. Once in the configuration mode you may right click anywhere on the page to get a context menu giving some options to control the layout. Once configuration has been completed just click the button in the top left to return to the page editing mode. The options that can be configured in this way include:

Option Role

Show Guides Shows the alignment guides

Show Grid Show the grid (with a minimum display spacing of 10 pixels).

Snap to grid Turns on or off the snap to grid facility where by components that are moved align themselves to a grid point.

Snap to guides Turns on or off the facility whereby components snap to the nearest guide.

Set Grid Spacing The separation of grid points in pixels.

Guide sensitivity Specifies the distance in pixels within which a component must be for it to be affected by a guide line.

Setup Columns Displays a dialog that allows the addition or guides to support rows and columns for layout purposes

Table 14-2 —

Guides

Drawing on the techniques used in desktop publishing and document layout, Carousel includes a facility to use guides. Guides are vertical or horizontal lines on the page to which components snap or gravitate while being positioned during page layout. Guides are configured on a page by page basis rather than at the level of individual panels. Guides therefore support layout across panels so it is easy to align components on a page wide basis rather than solely within an individual container as is the case with most layout managers. Guides are also visually intuitive so little effort is required to learn how guides function and indeed there should be few surprises when using guide layouts unlike layouts such as the GridBagLayout which is notoriously difficult to use.

• • • • 145 • • 14 – Layout Carousel, User Guide

Adding guides Guides can be configured on a page by page basis or on an application wide basis (as master guides) to help enforce layout rules across pages.

Figure 14-1 — Click to the toggle button to enter design mode.

Within the page designer adding guides is carried out by 1.Clicking the button in the top left intersection of the rulers. 2.Click and drag from either of the rulers onto the page 3.Release the mouse at the location for the new guide 4.Drag an existing guide to adjust its position 5.Click the button in the top left to exit the guide editing mode. To remove a guide simply enter the guide editing mode and drag a guide back to the ruler. Individual guides can then be configured by right clicking on them and choosing the Guide Options... menu option. This option allows control over how the guide is positioned at runtime.

Figure 14-1 — Configuring guides.

Guides can be positioned relative to one another or relative to the size at which the page is displayed so as to give a controlled final layout. The coordinates system used for the guide can also be expressed in relative terms of the page size instead of the absolute pixel size used at design time. The guide ID shown in the dialog is used to reference the guide by the

• • • 146 • • • Carousel, User Guide 14 – Layout

constraint specified for each component on the panel controlled by the guide layout manager.

Parameter Usage

ID An ID used by the component constraint to identify the guide. This option is read-only and is automatically configured by the editor. Guides are renumbered as they are repositions so that the leftmost or topmost guide is always zero.

Orientation A read-only property identifying the guide as vertical or horizontal

Position The guide position. Absolute positioning means the guide is position relative to the top left of the page. Relative positioning means the guide is position relative to the previous guide (to the left or above).

Coordinate The coordinates express the position of the guide either in absolute terms of pixels or in terms of the page size (scaled). For a scaled coordinate system the location is expressed as a percentage of the page size.

Location The guide location is its position. For a relative position the location value is the offset from the previous guide, whereas for an absolute location the value is the distance from the top left of the page.

Minimum Not yet implemented

Maximum Not yet implemented

Table 14-3 — Guide options

• • • • 147 • • 14 – Layout Carousel, User Guide

Several more options are available for configuration of the guides:

Figure 14-2 — Setting up row and column guides.

The area of guide sensitivity, that is the area within which a component will snap to the guide when moved can be highlighted (as illustrated above) by choosing the Show snap zone context menu option. The context menu is displayed by right clicking on a guide in edit mode. To enter the guide’s edit mode, toggle the button to the top left of the page at the vertex of the two rulers. In this mode the rulers are shown with a red background. Some of the guide options are context sensitive and depend on the guide on which the mouse is clicked. The options are described below:

Menu option Function

Snap to guides Toggles snapping of components to the guides

Snap to grid Toggles snapping of components to the grid.

Snap to hints Snap the component to the hints. Matches one component to the edges of another.

Show guides Toggle display of the guides

Show snap zone Toggle display of the zone within which components snap to the guides.

Table 14-4 — Guide configuration options

• • • 148 • • • Carousel, User Guide 14 – Layout

Menu option Function

Show grid Toggles display of the grid. The grid is shown as a set of dotted lines. Note that at lower grid spacings not every grid line is shown as doing so would obscure the display.

Set grid spacing Set the grid spacing in pixels

Setup columns... Setup a set of column and/or row guides

Guide options... Configure an individual guides. This option depends on the guide closest to the point where the mouse was clicked.

Table 14-4 — Guide configuration options

Snapping to guides As a component or set of components is dragged about within the page designer the edges of the components will automatically snap to the guide whenever within range. Guides will tend to cause a component to resize as a component is dragged but once a component goes out of range it will snap back to its original size. Snapping to hints In addition to the snapping of components to the guides the editor will show layout hints.

Figure 14-3 — Layout hints while positioning components.

These hints correspond to the edges of other components on the form. The hints therefore act as a form of automatic alignment of components. Later we plan to enhance this mechanism to support the alignment of baselines and the preferred platform component spacings (both features of the forthcoming JDK 6).

• • • • 149 • • 14 – Layout Carousel, User Guide

Setting up Columns While in the configuration mode you can choose to setup columns and rows to assist layout. The GuideChooser dialog appears when this option is chosen. You can use this dialog to quickly setup regularly spaced columns and rows. Once the guides have been added you may reposition the guides to best suit your layout needs. A form will typically require a number of different guide types with some absolute position and some relative or scaled Figure 14-4 — Setting up a set of row and column guides. positioning.

Using guides While it is possible to use guides purely for design time layout assistance the guides are of added benefit at runtime when a page is resized. To actually use the guides for this purpose it is necessary to use the GuideLayout manager. To use this Layout manager select the panel or container for which you wish to apply this option and set the layout property in the component’s property sheet (normally to the bottom right of the page designer). You may not see any immediate effect of choosing this layout manager but if you view the page’s XML you will see that additional constraint attributes are added to the components belonging to the affected panel. The constraints refer to the guide ID which you may have noticed while setting up the guides. The guides are numbered from zero, up from left to right and from top to bottom. The constraint is thus just the list of guides to which the left, top, right and bottom edges of the component are bound (a -1 value indicates an unbound edge). An example guide layout To illustrate the use of the guide layout let’s look at a sample form. The form is made up of two columns of labels and edits. Therefore a four column guide layout is created so that we can specify the spacing between the labels and edits and also the spacing between the columns, just as is shown above. The leftmost guide in each column and the last guide (vertical guides 0, 3 and 7) are scaled guides so that each holds its position relative to the page. The next guide is a relative guide specifying a fixed width for the label. Following this another relative guide with a fixed width

• • • 150 • • • Carousel, User Guide 14 – Layout

of 10 pixels is used to specify the spacing between label and edit. The edit field is then left to use the remaining space between the fixed guides and the scaled guides.

Figure 14-5 — A simple page using a guide layout at its default size.

The XML code for the complete form layout is shown below.

Table 14-5 — Guide layout

The constraints for each component specify the guide ID for the left, top, right and bottom edges. If the component is not bound to a guide then the ID can be specified as -1 and the x, y, w or h dimensions will be used to size and position the component as needed.

• • • • 151 • • 14 – Layout Carousel, User Guide

As of version 2.0.6 the guides can be stored in a separate file for reuse. Using this mechanism the guide files can be included using the following syntax:

Table 14-6 — Including guides

By convention the guide files are included in the guides subfolder of the pages folder. The .xml extension is optional. To see the guide layout in action we then resize the form. In the resized form each column still occupies half of the page although the relative size of the edit fields has increased.

Figure 14-6 — The same simple page using a guide layout following resizing.

Reusing guides Sometimes, to promote consistency across forms you may wish to reuse a set of guides. So far we have no explicit support for such a process with Carousel, however you can achieve the same effect by manually cutting and pasting the guide setup from one form to another. The entire guide declaration is contained in the Guides element at the start of each page, with a Guide entry for each vertical and horizontal guide.

Layout managers

Java introduced the concept of layout managers as a way of managing cross platform layout issues. There are a wide variety of layout managers available within the core Java libraries and from third parties. However for reasons of simplicity only a core set of layout managers is supported within Carousel.

LayoutManager Description

NULL This really isn’t a layout manager and instead components are positioned according to their absolute coordinates, specified at design time. This layout will not cause components to be repositioned as the container is resized.

Border A built-in Java AWT and Swing layout manager dividing the container into five predefined areas. See the Java documentation for more details.

Table 14-7 — Layout types

• • • 152 • • • Carousel, User Guide 14 – Layout

LayoutManager Description

Flow A built-in Java AWT and Swing layout manager. Components are arranged in the order in which they are added either as a row or column and depending on their preferred size. See the Java documentation for more details.

Card A built-in Java AWT and Swing layout manager. Arranges the component in a stack and displays only the selected component so that it completely fills the container. The first component added to a CardLayout object is the visible component when the container is first displayed. See the Java documentation for more details.

Box A built-in Java Swing layout manager. Similar to a FlowLayout, it arranges components along the X or Y axis. Provides slightly more control over the layout than the FlowLayout. See the Java documentation for more details.

Grid A built-in Java AWT and Swing layout manager. Arranges components in a grid or table like structure. See the Java documentation for more details.

GridBag A built-in Java AWT and Swing layout manager. Horribly complex to arrange and use. The GridBagLayout class is a flexible layout manager that aligns components vertically and horizontally, without requiring that the components be of the same size. Each GridBagLayout object maintains a dynamic, rectangular grid of cells, with each component occupying one or more cells, called its display area. See the Java documentation for more details.

Spring A built-in Java AWT and Swing layout manager. See the Java documentation for more details.

Scale A XUI layout manager that uses the absolute positions of the components and scales them in proportion to the container’s runtime size. Optionally allows fonts to be scaled.

Guide An extension of the ScaleLayout but using the Guides to add extra control over the scaling. The constraints for this layout are set automatically

Table 14-7 — Layout types

• • • • 153 • • 14 – Layout Carousel, User Guide

Carousel also includes a number of other layout managers used by some of its builders and wizards but not yet directly supported by the editor or by the basic XUI setup. These layout managers include:

LayoutManager Description

ColumnLayout A columnar layout for use in forms or the like, where a set of components is associated with a set of labels or other such controls and laid out in columns. The components are added in rows, but align to the columns. An example usage is in creating forms where a left hand column may contain labels or captions while the right hand column may contain the input fields. Indentation, spacing and padding may be added to control the layout and define the location of individual compoents.

LayerLayout The LayerLayout is intented for use with pages and panels where you want to overlay one set of components with another. All the children of the container with the LayerLayout are given the same size and hence overlay one another. The components are located in the order in which they are created. An application may have to set the opaque property of the panels added to the layers so that the layers appear as expected. The layering is intended to allow things like background decorations to be added and controlled easily. Layering may also be used to implement features such as overlays and modal/lock-out behavior, say for example overlaying a progress animation during a long running operation.

HtmlFormLayout A layout mimicing the way in which HTML lays out its components

Table 14-8 — Extra layouts

While these layout managers are not yet supported by the editor you can still make use of them by coding their use directly in Java. Some of the examples shipped with Carousel make use of these layouts.

Component hierarchies

It is often a good idea to subdivide an application and its pages into different areas. At the highest level and application may use the notion of a frameset to subdivide the screen or page. Typically a frameset is used where there are persistent elements to an application such as headers, footers or sidebars. Framesets are often used for navigation controls like toolbars, progress meters, structural views (tree views) and so on. Within an individual page further nesting of content may be used with various types of panels, scrollpanes, splitters and tab controls. Generally the more an application can subdivide the hierarchy of components the easier it is to control the layout of those controls.

• • • 154 • • • Carousel, User Guide 14 – Layout

The coordinates of child panels and of the components nested in a child panel are always relative to the parent or owner of the component or panel. The coordinates are also always measured from the top left of the panel that owns the component. Using a layout manager In using a layout manager in Carousel there are two steps to consider. First the parent container for a component must specify the type of layout manager it employs and secondly each component should specify the constraints that the layout manager should use to lay it out. Using XML the layout is added to the page or parent component as in the example below: