Get started with Jigloo, a GUI builder for Create a workflow application using an SWT GUI

Skill Level: Intermediate

Michael Galpin ([email protected]) Developer MichaelDKelly.com

03 Apr 2007

Jigloo is an Eclipse plug-in that enables you to build sophisticated graphical user interfaces (GUIs) rapidly that run on the ™ platform. It can be used to build -based applications and Standard (SWT)-based applications. It is an easy-to-use visual editor, so you can create the UI for your desktop application quickly. In this tutorial, we build a simple workflow application and use Jigloo to create its UI. Learn how easy it is to get started with Jigloo and to tap into its advanced features, such as visual inheritance. Finally, we test an application and package it for others to use.

Section 1. Before you start

This tutorial is intended for Java developers who want to build desktop applications and use the Eclipse plug-in called Jigloo to create the UI for their applications. The sample application makes use of XML, XML Schema, and JAXB, as well as some Java 5 features, such as Annotations and Generics.

About this tutorial

Java is a great platform for building rich desktop applications. When Java debuted in 1995, it shipped with the Abstract Window Toolkit (AWT). This was Java's first UI for building desktop applications. The release of JDK 1.2 in 1998 included Swing, a much-improved toolkit. Since then, there have been many improvements to Swing. It is now a powerful UI library that performs well on many different platforms. SWT is a competing UI toolkit for Java that offers many advantages. Now with Jigloo, you can rapidly build UIs targeting Swing or SWT. You can even build SWT

Get started with Jigloo, a GUI builder for Eclipse © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 1 of 49 developerWorks® ibm.com/developerWorks

applications that include Swing components, but that's beyond the scope of this tutorial.

In this tutorial, you'll learn about Jigloo by building a simple workflow application. You will use Jigloo, which is an Eclipse plug-in, to create the UI for the application. You will then build and test your application and package it for others to use.

Prerequisites

Familiarity with UI programming concepts like event handlers and data binding is helpful, but not absolutely necessary. Exposure to AWT/Swing or SWT is also helpful, but not a requirement.

System requirements

Eclipse V3.2 Since Jigloo is a plug-in for Eclipse, you need Eclipse, of course. The application will use SWT, and Eclipse also includes the SWT libraries you'll need for that.

Jigloo Jigloo is a plug-in for Eclipse. In the tutorial, you will see how to install Jigloo directly from Eclipse using Eclipse's powerful update manager.

Java 5+ The application in this tutorial makes use of some Java 5 features, such as Annotations and Generics. Download Java 5 or Java 6.

JAXB V2.0 The application in this tutorial uses XML as a data store and uses JAXB for parsing and serializing XML. If you're using Java 6, JAXB is included and there's nothing to do. If you're using Java 5, you'll need Sun's JAXB 2.0 Reference Implementation (RI).

Section 2. Overview

In this section, we look at the Jigloo plug-in and what you can do with it before walking through the steps to install it and set it up.

What is Jigloo?

Jigloo is a visual Java GUI builder. It is an Eclipse (and WebSphere® Studio) plug-in

Get started with Jigloo, a GUI builder for Eclipse Page 2 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

made by CloudGarden. It is free for noncommercial use. You can use Jigloo for commercial use by obtaining a professional license from CloudGarden.

What can you do with Jigloo?

Jigloo is a classic WYSIWYG editor for building Swing and SWT GUIs. If you want to develop a graphical, desktop application in Java, Jigloo is a great option. That's just the beginning, though.

Jigloo supports round-tripping. That means you can not only make visual changes that cause the underlying code to change but you can also directly edit the code and see the changes that causes in the GUI. This makes Jigloo a great choice if you have an existing, legacy GUI. It can interpret your existing application and allow you to edit visually. It also means you can use Jigloo in conjunction with other IDEs, like NetBeans or JBuilder.

Jigloo was built with Swing/SWT compatibility in mind. It supports the many layout options supported by either technology. Not only can you use either technology for building a new GUI but you can even convert between Swing and SWT using Jigloo. Jigloo can also let you mix in Swing components within a SWT application using the SWT_AWT bridge. In this tutorial, however, we will build our workflow application using an SWT GUI.

Installing Jigloo

Jigloo is an Eclipse plug-in, so it is very easy to install. If you've been using Eclipse for several years, you've probably downloaded a plug-in and installed it by simply unzipping it to the Eclipse installation directory. More recent versions of Eclipse have made this even easier. All you have to do is use Eclipse's Update Manager feature. To access this, select Help > Software Updates > Find and Install. This will open the Install/Update dialog. You'll want to select the "Search for new features to install" option. Then simply click Next, and you will go to the Update Site dialog.

If you've already installed Eclipse plug-ins, chances are, there will be other sites already listed in the "Sites to include in search." If that is the case, you want to make sure you've deselected any other sites in this list. Click New Remote Site, which will bring up the New Update Site dialog, as shown below.

Figure 1. New Update Site

Get started with Jigloo, a GUI builder for Eclipse © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 3 of 49 developerWorks® ibm.com/developerWorks

The important thing here is to enter http://cloudgarden1.com/update-site for the URL field. You can actually use anything you want for the Name field, but you'll probably want to use something descriptive like Jigloo Update Site. Click OK, and this will take you back to the Update Site dialog, but now the update site you just entered should appear in the list of sites to include. Click Finish. This will bring up the Search Results dialog. From the Search Results dialog, select Jigloo and clic Next. This will take you to the Feature License.

As mentioned, Jigloo can be used for free, but only for noncommercial use. Otherwise, you'll need to obtain a professional license from CloudGarden. After you've read the license, select the "I accept the terms in the license agreement" to accept the license. Then simply click Next. This will take you to the Installation details dialog. Click Finish. This will take you to the Feature Verification dialog. You can just click Install or Install All. This will initiate the installation. Eclipse will download the plug-in from CloudGarden and install it. Once it is done, you will probably need to restart Eclipse so it can finish the installation process.

Congratulations! You installed Jigloo. Like most Eclipse plug-ins, it is a painless experience. You are now ready to start using Jigloo. Start with a little configuration.

Setting up Jigloo

Create a new Java project using Eclipse. Select File > New > Project, then select Java Project. Clicking Next will take you to the New Project dialog.

In this tutorial, the project is called "workflow." You can use any name you want. Once you've given it a name, click Finish.

As mentioned, you can build Swing or SWT GUIs using Jigloo. In this tutorial, we will build an SWT GUI. This requires a little extra configuration. You need to add the SWT JAR to your project's classpath. To do this, select your project and then File > Properties from the main menu. This will bring up the Project Properties screen. Select the Java Build Path in the left navigation, and this will bring up the Java Build Path dialog.

Click on the Libraries tab, then the Add External JARs button. This brings up a file explorer dialog. You'll want to navigate to $ECLIPSE_HOME/plug-ins, where

Get started with Jigloo, a GUI builder for Eclipse Page 4 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

$ECLIPSE_HOME is the location of your Eclipse installation, as shown below.

Figure 2. Eclipse plug-ins directory

You'll want to look for the org.eclipse.swt.X.X.X.jar. The X.X.X. will be different depending on what platform you're using and the exact version of Eclipse. Click Open, then click OK back in your Java Build Path screen.

You've created a basic Java project and added the SWT library to its classpath. You are now ready to start using Jigloo to design and develop the workflow application.

Workflow application

Our example is a very simple workflow application. There will be two kinds of users in our application: workers and managers. The application will be used by workers to enter in a purchase request. They will be able to enter in pertinent information about the purchase order. They will also be able to see the status of all the orders entered. Each purchase order can have one of three possible statuses: pending, approved, rejected. The application will be a little different for managers. A manager will be able to see all purchase orders with pending status. The manager will then be able to approve or reject the purchase order.

This will be a simple application, so we won't worry about users logging in and out. Instead, we will simply present a list of users in the system; an application user can simply pick the user he wants to log in as. In a real workflow system, concurrency is

Get started with Jigloo, a GUI builder for Eclipse © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 5 of 49 developerWorks® ibm.com/developerWorks

a big issue. We won't worry about that for our application, since it won't be running on multiple systems. A real workflow system also needs to persist the workflow data in a shared repository, usually a relational database. We'll make ours simpler by simply persisting the data in an XML file. We'll use JAXB for marshalling and unmarshaling the XML data.

We dive into actually writing the code for our GUI next.

Section 3. Setting up the GUI

Now that we have the basic design for our system, it's time to start writing some code. We'll concentrate on the GUI and using Jigloo.

Designing the GUI for our workflow application

Let's get started designing the GUI for our workflow application. First, let's create a package for our workflow application. Right-click on your project in the Package Explorer pane and select New > Package. Let's call our base package org.developerworks.workflow. Click Finish.

Now let's create our application in this package. Right-click on the package and select New > Other. This brings up the "Select a wizard" screen. All the Jigloo wizards are found in the GUI Forms folder in this screen. Open that folder, then open the SWT folder and select the SWT Main Application option, shown in Figure 3.

Figure 3. Select a wizard

Get started with Jigloo, a GUI builder for Eclipse Page 6 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

Click Next to kick off the New SWTApp wizard. Let's call our main class WorkflowMain, as shown in Figure 4.

Figure 4. New SWTApp wizard

Get started with Jigloo, a GUI builder for Eclipse © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 7 of 49 developerWorks® ibm.com/developerWorks

You can leave everything else as is and just click Finish.

The Jigloo visual designer view

Now your Eclipse workspace should look something like Figure 5.

Figure 5. Eclipse displaying WorkflowMain

Get started with Jigloo, a GUI builder for Eclipse Page 8 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

There are many interesting things to notice here. First, our main window shows a custom view used by Jigloo. This view is a split screen. At the top is the Jigloo visual designer. We'll do a lot of work in this dialog, as it allows us to design our GUI by using . We'll talk a lot more about this view. In the bottom of the split screen is the Java code for our application, which we'll get into later. Notice how Jigloo has already generated a lot of code for us.

Below the main window, we see the GUI Properties window. This view shows us detailed properties for any visual component selected in the visual designer window. We'll use this view a lot, too. Finally, notice that in the Package Explorer view there is another package present: com.cloudscape.resource. This package contains generated class SWTResourceManager. As its name implies, this class manages SWT resources such as fonts, colors, and images. If you've ever used visual design tools like Jigloo, you've probably seen classes like this. Often these include stern warnings about not modifying anything in the class since they are either very brittle and modification will probably cause exceptions, or whatever changes you make will probably be overwritten. That's not the case for the SWTResourceManager. You can modify it to change the resources that it manages, like the default font for your application, and Jigloo will not overwrite the changes, and it won't cause anything to break.

Get started with Jigloo, a GUI builder for Eclipse © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 9 of 49 developerWorks® ibm.com/developerWorks

Let's start using the visual designer. If you're used to working with Eclipse, you probably know you can maximize any window by simply double-clicking its name. Let's do that and maximize the WorkflowMain window, as shown in Figure 6.

Figure 6. WorkflowMain maximized

Not only does this give our visual designer more real estate to work with but it makes it easier to access the GUI properties (bottom right corner.) It also shows a hierarchical representation of our GUI in the top right corner. It's pretty simple right now, but as we add more components to our GUI, we'll see them added to the hierarchy. It also gives us useful controls for previewing our application or running it to test it. Now that we're a little more familiar with the visual designer, let's start using it to configure our application.

Developing with the visual designer

If you've developed a Swing or SWT application before, you're probably familiar with the many kinds of layout managers available. Layout managers have always been a powerful feature of Java GUI applications. They allow for different algorithms to be applied when laying out a GUI. Java's motto has always been "write once, run everywhere," and these layout algorithms are consistent with this. They allow for a GUI application's layout to work regardless of the size and geometry of the screen or window displaying the GUI.

Get started with Jigloo, a GUI builder for Eclipse Page 10 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

The only downside to these layout algorithms is that they can present a learning curve to developers, especially those from other platforms who are used to absolute positioning of elements. With absolute positioning, you simply put your component where you want it to be on the screen, and that's where it will be. The problem with this kind of layout is that it "breaks" when the screen size varies.

Since this is meant to be a simple example application, we will use an absolute layout to make things simple. To do this, we'll use the GUI properties. Click on the Layout tab and change the value of Layout to Absolute, as shown in Figure 7.

Figure 7. Configure layout

Get started with Jigloo, a GUI builder for Eclipse © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 11 of 49 developerWorks® ibm.com/developerWorks

Get started with Jigloo, a GUI builder for Eclipse Page 12 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

Next, let's make our main application a little bigger. To do this, simply grab the main window by the bottom right corner and stretch it to whatever size you like.

Now we're ready to start adding visual components to our application. We'll need to be able to switch between different kinds of users. We could provide a login screen that asks for user name and password, but let's keep things simple. Let's just have a drop-down list where you can select what user to log in as.

The visual designer has a toolbar at its top that contains various visual components you can select and add to the application. This is a tabbed toolbar. We want to add a control, so select the Controls tab. Each control has an intuitive icon, but you can also mouseover each control to see its name. Select the combo control and drop it on our main window. This will bring up a properties editor for our new control, as shown in Figure 8.

Figure 8. Property editor for combo control

We've changed the name of the component to be something intuitive (userListCombo) and given it some default text of Users. Click OK, and you should see it inside your application.

Get started with Jigloo, a GUI builder for Eclipse © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 13 of 49 developerWorks® ibm.com/developerWorks

Now we have a way to pick and change users. When we pick a user, what do we want to happen? For workers, they should be able to see all of the purchase orders they've entered to date and the status of those purchase orders. For managers, they need to see the orders that are pending so they can approve or reject the orders. Let's create a table to display the purchase orders.

To add a table, switch the toolbar tab to the Containers tab. Look for the icon that looks like a table and select it. Once you select the table, you can use the mouse to put it anywhere you want it. Let's put it just below our user combo list. Once you select a location for it, a dialog will appear to ask you to name the table. Again, let's use an intuitive name, so type in purchaseOrderTable. Click OK, and your table should appear in the visual designer.

You can expand the table to make it bigger by grabbing its bottom right corner. Let's configure the table a little more. Its properties are in the GUI Properties view in the bottom right of Eclipse window. Click the Properties tab and expand the Expert list of properties. Change the lines-visible property to true by clicking the checkbox, as shown in Figure 9.

Figure 9. Editing table properties

Let's add some columns to our table. To do this, use the Containers tab on the toolbar to select the Add TableColumn to Table icon, right next to the table icon we selected earlier. Now you can simply drop the TableColumn into the

Get started with Jigloo, a GUI builder for Eclipse Page 14 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

purchaseOrderTable, and this will bring up the TableColumn property editor. Again, use a descriptive name, poItemNameColumn, since this will have the name of the item that was ordered. The text is going to the label of the column, so type in Item for it and click OK.

After we've added this, the visual designer should look something like Figure 10.

Figure 10. Visual designer after one column added

At this point, you may not see the name of the column. If so, fix that by accessing the table's expert properties again. Just click on the table, and the GUI Properties will switch back to the table. Open up the Expert section look for the property called headerVisible, as shown in Figure 11.

Figure 11. Editing table properties

Get started with Jigloo, a GUI builder for Eclipse © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 15 of 49 developerWorks® ibm.com/developerWorks

Get started with Jigloo, a GUI builder for Eclipse Page 16 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

That property has a checkbox, so it can be set to true or false. Switch it to true, and now you should see the header on the table and the item label for the first column.

Let's go ahead and add four more columns: Price, Quantity, Status, and ID. After we're done, the designer should look like Figure 12.

Figure 12. All columns added to table

Now we can display all orders as needed. We need a way to either approve or reject orders. Let's add a couple of buttons to do this, one for each operation. To add a button, switch to the Controls tab on the toolbar and pick the icon for the Button control. Again, you can just drag the button to wherever you want to put it. Let's put it just below our table. Once you drop it, you'll be greeted with the button's property editor dialog. Let's make the first button the one for approving a purchase order, so we'll name it approveButton and give it a text label of Approve. Click OK, and the visual editor should show your new button.

Similarly, we'll add a Reject button to the application. After you've done that, the visual designer should look like Figure 13.

Figure 13. Both buttons added

Get started with Jigloo, a GUI builder for Eclipse © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 17 of 49 developerWorks® ibm.com/developerWorks

You might notice in the picture that our two buttons aren't exactly lined up. It's hard to eyeball such things, but luckily, Jigloo provides an easy way to line up components. Simply pick the two components -- in this case, the two buttons -- and use the styling toolbar on the left side of the designer. We'll use the Align tops of selected elements button, as shown in Figure 14.

Figure 14. Aligning buttons

Get started with Jigloo, a GUI builder for Eclipse Page 18 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

The buttons should look nice and lined up. Jigloo makes it easy to make our GUI look very professional.

Now we can pick users, see purchase orders, and even approve or reject a purchase order. All we need to do is add a purchase order. We'll create a form for entering the data for a new purchase order. The form will involve several components corresponding to the various types of data needed to model a purchase order. Let's create a grouping of these components. That will give us a way to address all the components as a group, which could be very useful. For example, we might want to make it so only certain users can add a new purchase order. For such users, we might want to make the form invisible. It will be easier to do that if all the elements in the form are grouped together.

To create this grouping, we will add a Composite component to our application. Change to the Containers tab in the toolbar and select the Composite icon, as shown in Figure 15.

Figure 15. Add Composite using toolbar

Get started with Jigloo, a GUI builder for Eclipse © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 19 of 49 developerWorks® ibm.com/developerWorks

Drop it wherever you want. There's a large chunk of open space on the right side of our application, so that's where we'll drop it. This will not surprisingly bring up the Composite's Property Editor dialog, as shown in Figure 16.

Figure 16. Composite property editor

Get started with Jigloo, a GUI builder for Eclipse Page 20 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

We'll call our Composite itemForm, since that's what it's intended to hold. Make sure to change its Layout to Absolute. That's because a Composite can have its own . After you click OK, you should see the Composite in the visual designer, as shown in Figure 17.

Figure 17. Composite in visual designer

Get started with Jigloo, a GUI builder for Eclipse © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 21 of 49 developerWorks® ibm.com/developerWorks

We can make the Composite bigger by grabbing it by its bottom right corner. Let's expand it so that we have plenty of room to add the form elements.

Now let's design our form. Our form will mostly be text boxes and labels. We'll use the toolbar for adding these elements to our form. Switch to the Controls tab and select the label icon. Just as you might expect, you can drop this wherever you want. Put it at the top left of our form container. Once again, this will bring up the usual property editor, this time for the Label Control, as shown in Figure 18.

Figure 18. Label Control property editor

Get started with Jigloo, a GUI builder for Eclipse Page 22 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

You should now see the label in the visual designer. Once again, you can resize it by dragging its corners.

Once we have the label, let's add a text box next to it for users to enter in the name of the item in the purchase order. Select the Text Control from the toolbar. By now, you know the routine: drop it where you want it, and it will bring up the property editor for it as shown in Figure 19.

Figure 19. Text Control property editor

We gave it a descriptive name, formItemText. We also cleared the Text value. This would be used for some kind of default value, but we don't really need that. Now we should see our text box in the visual editor and we can resize it.

We'll go ahead and repeat this for two more fields: Price and Quantity. Each gets a label and a text box. Once they are added, our visual editor should look like Figure 20.

Figure 20. Price and quantity fields added

Get started with Jigloo, a GUI builder for Eclipse © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 23 of 49 developerWorks® ibm.com/developerWorks

Notice that we did give a default value for quantity of 1. Those are all the basic data elements we need for our purchase order. Now we just need a way to submit our form for processing. Let's add a button for this. We could do this just as we did earlier, by selecting the Button Control from the toolbar, etc. Let's use a different technique this time. Simply right-click inside the Composite and select Add SWT Object > Button, as shown in Figure 21.

Figure 21. Adding button using context menu

Get started with Jigloo, a GUI builder for Eclipse Page 24 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

This will take us to the familiar property editor dialog. Name the component addButton and give it the text Add PO. Clicking OK, we see our new button the designer, as shown in Figure 22.

Figure 22. Add button added

Get started with Jigloo, a GUI builder for Eclipse © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 25 of 49 developerWorks® ibm.com/developerWorks

The biggest difference between this method and using the toolbar is that we'll need to adjust its position and alignment relative to the other controls. This gives us an opportunity to use another of the alignment controls. Select the three text boxes and the add button (use the shift key for multiple selections), and click on the Space selected elements evenly vertically," as shown in Figure 23.

Figure 23. Spacing elements evenly vertically

Get started with Jigloo, a GUI builder for Eclipse Page 26 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

Feel free to explore some of the other alignment controls. Once you're done the final UI should look something like Figure 24.

Figure 24. Final UI design

Get started with Jigloo, a GUI builder for Eclipse © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 27 of 49 developerWorks® ibm.com/developerWorks

Previewing the GUI

We have a pretty picture of our GUI now. It's not functional yet, since we haven't hooked up any data to it. We'll get to that shortly, but this is a good time to take advantage of another one of Jigloo's nice features: Preview. Click on Preview in the top right window. This will bring up a graphical preview of the GUI, as shown in Figure 25.

Figure 25. Preview of Workflow GUI

Get started with Jigloo, a GUI builder for Eclipse Page 28 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

This is exactly what our final application will look like. One great thing you'll notice is that this looks just like a Windows® application. That's because we used SWT on Windows. As mentioned, it uses native widgets.

Section 4. Creating the data model for the application

If you're familiar with classic Model-View-Control (MVC) architecture, you recognize that what we've done so far is create the view of our application. That's one of the areas where Jigloo really shines. At some point, it's time to create the model. That means writing some Java code to read and act upon the data that drives our system. Jigloo shines at this, too, but it does it without even trying. Jigloo is simply a plug-in for Eclipse, so you have the full power of Eclipse always at your fingertips when using Jigloo. Since Eclipse is great for writing Java code and working with data, Jigloo is also great for doing these things.

Creating the schema

As mentioned, we will store our data in XML and use JAXB for reading and writing to our XML file. That means we need to create a schema.

Listing 1. Workflow XML schema

Get started with Jigloo, a GUI builder for Eclipse © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 29 of 49 developerWorks® ibm.com/developerWorks

We can use JAXB to create Java classes that will bind to XML files that correspond to the schema. If you're using Java 6, JAXB is built in. If you're using Java 5, you need to download it from Sun. You'll want to use the command-line tool xjc. You'll simply use xjc workflow.xsd for example. This will cause the schema compiler to parse workflow.xsd and generate the classes. Then you can simply copy those classes to your project. Let's also copy our schema to our project and create an XML directory for this file. Then, create a sample XML file.

Listing 2. Initial XML data

Get started with Jigloo, a GUI builder for Eclipse Page 30 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

homer worker bart manager normal 2001-01-01 2001-01-01 stapler A great stapler 2 http://www.thinkgeek.com/homeoffice/gear/61b7/ 21.99 pending 0

Once all these artifacts are added, our Package Explorer should look like Figure 26. (If necessary, add the JAXB jars to the Java Build Path.)

Figure 26. Package explorer with JAXB classes and XML files added

Get started with Jigloo, a GUI builder for Eclipse © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 31 of 49 developerWorks® ibm.com/developerWorks

Data access

You might have noticed a couple of other files in the explorer: WorkflowDao and XmlWorkflow. WorkflowDao is an interface defining the operations we would need to do with our data (see Listing 3).

Listing 3. WorkflowDao interface

package org.developerworks.workflow; import java.util.List; public interface WorkflowDao { public List getUsers(); public List getAllOrders(); public List getAllPendingOrders(); public List getOrdersForUser(int userId); public void saveOrder(PurchaseOrder order); public void setOrderStatus(int orderId, OrderStatus status); }

Get started with Jigloo, a GUI builder for Eclipse Page 32 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

We are using a classic Data Access Object pattern. We simply define the interface and code our application to this interface. We'll use an XML JAXB-based implementation in this application, but by using this design, we could easily switch to a different implementation, such as a database-based implementation. The implementation of our interface is XmlWorkflow.

Listing 4. XmlWorkflow interface implementation

package org.developerworks.workflow; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStream; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; public class XmlWorkflow implements WorkflowDao { private static final String DATA_FILE = "data.xml"; private static XmlWorkflow instance; private Workflow workflow; private XmlWorkflow() { try { JAXBContext ctx = this.getContext(); Unmarshaller unm = ctx.createUnmarshaller(); File dataFile = this.getDataFile(); InputStream inputStream; if (dataFile.exists() && dataFile.length() > 0){ inputStream = new FileInputStream(dataFile); } else { inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("xml/"+DATA_FILE); } JAXBElement element = (JAXBElement) unm.unmarshal(inputStream); this.workflow = (Workflow) element.getValue(); } catch (JAXBException e) { e.printStackTrace(); throw new RuntimeException("Failed to read data file",e); } catch (FileNotFoundException e) { e.printStackTrace(); throw new RuntimeException("Could not open data file", e); } } public static XmlWorkflow getInstance(){ if (instance == null){ instance = new XmlWorkflow(); } return instance; } public List getAllOrders() { return this.workflow.getPo(); } public List getAllPendingOrders() { List allOrders = this.getAllOrders(); List pending = new ArrayList(); for (PurchaseOrder order : allOrders){ if (order.getStatus().equals(OrderStatus.PENDING)){

Get started with Jigloo, a GUI builder for Eclipse © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 33 of 49 developerWorks® ibm.com/developerWorks

pending.add(order); } } return pending; } public List getOrdersForUser(int userId) { List allOrders = this.getAllOrders(); List userOrders = new ArrayList(); for (PurchaseOrder order : allOrders){ if (order.getSubmittedBy().intValue() == userId){ userOrders.add(order); } } return userOrders; } public List getUsers() { return this.workflow.getUser(); } public void saveOrder(PurchaseOrder order) { int index = 0; for (PurchaseOrder po : this.workflow.getPo()){ if (po.getId().intValue() == order.getId().intValue()){ this.workflow.getPo().set(index, order); this.saveData(); return; } index++; } // add new order order.setId(new BigInteger(Integer.toString(this.workflow.getPo().size()))); this.workflow.getPo().add(order); this.saveData(); } public void setOrderStatus(int orderId, OrderStatus status) { for (PurchaseOrder po : this.workflow.getPo()){ if (po.getId().intValue() == orderId){ po.setStatus(status); this.saveData(); return; } } } private void saveData(){ File dataFile = this.getDataFile(); try { JAXBContext ctx = this.getContext(); Marshaller marshaller = ctx.createMarshaller(); FileOutputStream stream = new FileOutputStream(dataFile); marshaller.marshal(this.workflow, stream); } catch (JAXBException e) { e.printStackTrace(); throw new RuntimeException("Exception serializing data file",e); } catch (FileNotFoundException e) { e.printStackTrace(); throw new RuntimeException("Exception opening data file"); } } private File getDataFile() { String tempDir = System.getProperty("java.io.tmpdir"); File dataFile = new File(tempDir + File.separatorChar + DATA_FILE); return dataFile; } private JAXBContext getContext() throws JAXBException { JAXBContext ctx = JAXBContext.newInstance("org.developerworks.workflow"); return ctx; }

Get started with Jigloo, a GUI builder for Eclipse Page 34 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

public static void main(String[] args){ XmlWorkflow dao = XmlWorkflow.getInstance(); List users = dao.getUsers(); assert(users.size() == 2); for (User user : users){ System.out.println("User: " + user.getUsername() + " ID:" + user.getId()); } List orders = dao.getAllOrders(); assert(orders.size() == 1); for (PurchaseOrder order : orders){ System.out.println("Order:" + order.getItemName() + " ID:" + order.getId() + " Status:" + order.getStatus()); } PurchaseOrder order = orders.get(0); order.setStatus(OrderStatus.APPROVED); order.setProcessedBy(new BigInteger("1")); dao.saveOrder(order); } }

Notice that we read from our sample file initially, but we save changes to a file called data.xml that will be stored in the system temporary directory. Not exactly the safest place for our data, but good enough for this sample application. You'll also notice there's a simple main method in this class. This allows for a simple unit test of the JAXB mechanics. Also, if you're using Java 5, you'll need to add the JAXB jars to the classpath of your project. You may want to go ahead and copy them to your project, or you can reference them in a location outside the project.

Initializing the application

Before we can interact with our application, we need to initialize everything. First we need to declare some model objects to use within the application. Just add the lines in Listing 5 to the member variable declaration in WorkflowMain.

Listing 5. Model objects declared

// Data Model Objects private java.util.List users; private User user; // Service Object private WorkflowDao dao = XmlWorkflow.getInstance();

To access the code, right-click the Workflow.java file and choose Open With > Java Editor.

We'll modify the code to the application's initGUI() method. We'll create a private method for initializing our list of users.

Listing 6. Creating the users method

private void initUserList(){ this.users = dao.getUsers(); for (User u : users){ this.userListCombo.add(u.getUsername()); } }

Get started with Jigloo, a GUI builder for Eclipse © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 35 of 49 developerWorks® ibm.com/developerWorks

Call this method in the initGUI() right after the userListCombo is defined.

Listing 7. Calling the users method

{ userListCombo = new Combo(this, SWT.NONE); userListCombo.setText("Users"); userListCombo.setBounds(28, 35, 105, 21); this.initUserList(); }

Gluing together the view and the model using events

We have our view and our model, so we just need to glue them together. We need a controller. SWT (and Swing) employ a simple technique used by virtually all UI frameworks: They are event-driven systems. We'll use events to know when the invoke operations on our model and modify our view.

Let's go back to our visual designer. The first UI event we need to associate with our model is when a user is selected from the user combo list. Select the combo control and change to the Events tab in the GUI Properties view, as shown in Figure 27.

Figure 27. Accessing the combo controls events

Get started with Jigloo, a GUI builder for Eclipse Page 36 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

You'll see several listeners to the combo control. We'll pick the

Get started with Jigloo, a GUI builder for Eclipse © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 37 of 49 developerWorks® ibm.com/developerWorks

SelectionListener. This listener fires a SelectionEvent whenever a selection is made in the combo control. We can choose to handle it inline with an anonymous method, or we can define a method for handling the event. We'll choose the latter. This will cause the code editor to show a generated method userListComboWidgetSelected. The code for handling this event is shown in Listing 8.

Listing 8. User combo list slected code

private void userListComboWidgetSelected(SelectionEvent evt) { int index = this.userListCombo.getSelectionIndex(); if (index >= 0){ this.user = this.users.get(index); System.out.println("User selected="+this.user.getUsername()); purchaseOrderTable.removeAll(); java.util.List orders; boolean isManager = this.user.getRole().equals(Role.MANAGER); if (isManager){ orders = dao.getAllPendingOrders(); } else { orders = dao.getOrdersForUser(this.user.getId().intValue()); } this.approveButton.setVisible(isManager); this.rejectButton.setVisible(isManager); for (PurchaseOrder order : orders){ displayPurchaseOrder(order); } } }

There's a lot going on here. First, we figure out if the user is a manager. If not, we show all of his purchase orders. If it's a manager, we'll only show the pending offers. Next, we disable the approve/reject buttons if the user is not a manager. Finally, we display all the orders we retrieved from the data access object in the purchaseOrderTable.

Now we'll add events to our Approve button. To do this, select the Approve button in the visual designer and go to the Events tab in the GUI Properties. Once again, we'll pick the selection event, as this will be fired when the button is selected, as shown in Figure 28.

Figure 28. Configuring Approve button selection event

Get started with Jigloo, a GUI builder for Eclipse Page 38 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

Get started with Jigloo, a GUI builder for Eclipse © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 39 of 49 developerWorks® ibm.com/developerWorks

Then we add code to handle this event.

Listing 9. Approve button selection event code

private void approveButtonWidgetSelected(SelectionEvent evt) { TableItem[] selected = this.purchaseOrderTable.getSelection(); if (selected != null){ for (TableItem item : selected){ this.dao.setOrderStatus(Integer.parseInt(item.getText(4)), OrderStatus.APPROVED); item.setText(3, OrderStatus.APPROVED.toString()); } } }

We'll do something very similar for the reject button: add a selection event listener and execute similar code. The only difference will be that we change the status on the order to REJECTED instead of APPROVED.

Listing 10. Reject button code

private void rejectButtonWidgetSelected(SelectionEvent evt) { TableItem[] selected = this.purchaseOrderTable.getSelection(); if (selected != null){ for (TableItem item : selected){ this.dao.setOrderStatus(Integer.parseInt(item.getText(4)), OrderStatus.REJECTED); item.setText(3, OrderStatus.REJECTED.toString()); } } }

All that's left is handling the Submit button on our form. That will let us add purchase orders. This is done just like the other buttons. Add an event handler for its selection event, as shown in Figure 29.

Figure 29. Add PO button selection listener

Get started with Jigloo, a GUI builder for Eclipse Page 40 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

Get started with Jigloo, a GUI builder for Eclipse © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 41 of 49 developerWorks® ibm.com/developerWorks

Add the code for handling the event.

Listing 11. Add PO button event-handler code

import java.math.BigDecimal; import java.math.BigInteger; import java.util.GregorianCalendar; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; ... private void addButtonWidgetSelected(SelectionEvent evt) { try { this.addPurchaseOrder(); } catch (Exception e) { throw new RuntimeException("Exception adding purchase order",e); } this.formItemText.clearSelection(); this.formPriceText.clearSelection(); this.formQuantityText.clearSelection(); } private void addPurchaseOrder() throws Exception{ String item = this.formItemText.getText(); String priceString = this.formPriceText.getText(); String quantityString = this.formQuantityText.getText(); BigDecimal price = new BigDecimal(priceString); BigInteger quantity = new BigInteger(quantityString); PurchaseOrder po = new PurchaseOrder(); int num = this.dao.getAllOrders().size(); String numString = Integer.toString(num); BigInteger newId = new BigInteger(numString); po.setId(newId); po.setItemName(item); po.setPrice(price); po.setQuantityRequested(quantity); po.setPriority(Priority.NORMAL); po.setStatus(OrderStatus.PENDING); po.setSubmittedBy(this.user.getId()); GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance(); DatatypeFactory factory = DatatypeFactory.newInstance(); XMLGregorianCalendar now = factory.newXMLGregorianCalendar(cal); po.setDateRequested(now); this.dao.saveOrder(po); this.displayPurchaseOrder(po); } private void displayPurchaseOrder(PurchaseOrder order) { String[] row = new String[] {order.getItemName(), order.getPrice().toString(), order.getQuantityRequested().toString(), order.getStatus().toString(), order.getId().toString()}; TableItem tableItem = new TableItem(purchaseOrderTable,0); tableItem.setText(row); this.purchaseOrderTable.showItem(tableItem); }

Test the GUI

Time to test our GUI. Right-click on the class and select Run As > SWT Application, as shown in Figure 30.

Figure 30. Running the application

Get started with Jigloo, a GUI builder for Eclipse Page 42 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

This should launch the application.

Figure 31. The workflow application

The default data has a pending PO, so pick the user bart, and we can approve the PO.

Figure 32. Approving an order

Get started with Jigloo, a GUI builder for Eclipse © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 43 of 49 developerWorks® ibm.com/developerWorks

Switch over to homer and see the PO's status.

Figure 33. Worker viewing his POs

You can add a new purchase order now.

Figure 34. Adding a PO

Get started with Jigloo, a GUI builder for Eclipse Page 44 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

Clicking Add PO should add it to the table.

Figure 35. New PO added

Switch to bart, and we can approve or reject.

Figure 36. Updated manager screen

Get started with Jigloo, a GUI builder for Eclipse © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 45 of 49 developerWorks® ibm.com/developerWorks

Section 5. Summary

In this tutorial, you've seen how to create a basic GUI using Jigloo. You've added a few different containers and controls. You've seen how to use events from those controls to tie-in to a model implementing some kind of business logic. There's a lot you can do from here. You're ready to dive into Jigloo's advanced features. Use can use Jigloo to:

• Extract your forms to separate and reusable components • Use these components in other applications and even extend them using visual inheritance • Add Swing components • Convert the entire application to Swing The schema supports more optional properties, so you can make the form more complex. You can add date pickers and combo controls for some of these data elements.

Review the Resources for additional documentation and ideas for using Jigloo in your applications.

Get started with Jigloo, a GUI builder for Eclipse Page 46 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

Downloads

Description Name Size Download method Part 4 source code os-eclipse-jigloo.workflow.zip18KB HTTP

Information about download methods

Get started with Jigloo, a GUI builder for Eclipse © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 47 of 49 developerWorks® ibm.com/developerWorks

Resources

Learn • Get the latest information about the Eclipse platform at Eclipse.org. • Check out Jigloo at CloudGarden. • Learn about creating SWT applications in the developerWorks article series "A gentle introduction to SWT and JFace." • Learn about migrating legacy Swing applications to the higher-performing SWT platform in "Migrate your Swing application to SWT." • Examine the strengths and weaknesses of SWT, Swing, or AWT in "SWT, Swing, or AWT: Which is right for you?" • Learn all about creating Eclipse plug-ins like Jigloo in the article about Eclipse's plug-in system. • Learn about creating Eclipse Rich Client Platform applications using SWT in "Customizing Eclipse RCP Applications." • Learn all about the various SWT widgets in the Eclipse SWT Widget reference manual. • Get acquainted with Swing in this developerWorks article "Introduction to Swing." • For an introduction to the Eclipse platform, see "Getting started with the Eclipse Platform." • Check out the "Recommended Eclipse reading list." • Browse all the Eclipse content on developerWorks. • Expand your Eclipse skills by checking out IBM developerWorks' Eclipse project resources. • To listen to interesting interviews and discussions for software developers, check out check out developerWorks podcasts. • Stay current with developerWorks' Technical events and webcasts. • Check out upcoming conferences, trade shows, webcasts, and other Events around the world that are of interest to IBM open source developers. • Visit the developerWorks Open source zone for extensive how-to information, tools, and project updates to help you develop with open source technologies and use them with IBM's products. Get products and technologies • Download the Eclipse Platform and get started with Eclipse now. • Download Jigloo.

Get started with Jigloo, a GUI builder for Eclipse Page 48 of 49 © Copyright IBM Corporation 1994, 2008. All rights reserved. ibm.com/developerWorks developerWorks®

• Check out the latest Eclipse technology downloads at IBM alphaWorks. • Innovate your next open source development project with IBM trial software, available for download or on DVD. Discuss • The Eclipse Platform newsgroups should be your first stop to discuss questions regarding Eclipse. (Selecting this will launch your default Usenet news reader application and open eclipse.platform.) • The Eclipse newsgroups has many resources for people interested in using and extending Eclipse. • Subscribe to the Eclipse Platform SWT mailing list to get the latest Eclipse news. • Participate in developerWorks blogs and get involved in the developerWorks community.

About the author

Michael Galpin Michael Galpin has been developing Java software professionally since 1998. He currently works for eBay. He holds a degree in mathematics from the California Institute of Technology.

Get started with Jigloo, a GUI builder for Eclipse © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 49 of 49