Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

Build GUIs with the Eclipse Visual Editor project

A graphical tool for building graphical interfaces

David Gallardo (david@gallardo.org), Software consultant
David Gallardo, a Studio B author, is an independent software consultant and author specializing in software internationalization, Java Web applications, and database development. He has been a professional software engineer for over fifteen years and has experience with many operating systems, programming languages, and network protocols. His recent experience includes leading database and internationalization development at a business-to-business e-commerce company, TradeAccess, Inc. Prior to that, he was a senior engineer in the International Product Development group at Lotus Development Corporation where he contributed to the development of a cross-platform library providing Unicode and international language support for Lotus products including Domino. David is co-author of Eclipse In Action: A Guide for Java Developers (Manning, 2003). He can be reached at david@gallardo.org.

Summary:  Like many Eclipse.org projects, the goal of the Visual Editor project is to build a tool for building tools — in this case, tools for building graphical user interfaces (GUIs). The Visual Editor project has released a reference implementation. The Visual Editor release 0.5 is a GUI builder for AWT/Swing applications, a long-awaited Eclipse feature. Release 1.0 includes support for SWT. Get an overview of Visual Editor and the technology behind it, along with a short demonstration of Visual Editor V0.5's features for building AWT/Swing applications and a preview of the SWT support in Visual Editor V1.0.

Date:  14 Mar 2006 (Published 04 May 2004)
Level:  Introductory
Also available in:   Japanese  Portuguese

Activity:  322706 views
Comments:  

Editor's note

This article was written in May 2004, when the current version of Eclipse was 2.1. As a result, some details here not up to date, but it remains a basic introduction to the Eclipse Visual Editor project and related libraries.


Introducing the Eclipse Visual Editor project

Read through any discussion thread on the relative merits of Eclipse and its competitors, and you'll find mention of various features that might be better, worse, or entirely missing in one or the other. Until recently, the one thing that always seemed to come up regarding Eclipse is its lack of a GUI builder: a graphical tool for building GUIs. Happily, this was remedied by the November 2003 launch of the Eclipse Visual Editor Project and the release soon after of Visual Editor V0.5, which allows you to create AWT/Swing applications with a complete WYSIWYG graphical editor.

Like Eclipse, Visual Editor is based on a code contribution by IBM®. Developers familiar with the Visual Editor in WebSphere® Studio Application Developer V5.x will find Eclipse's Visual Editor to be nearly identical. To learn how to use Visual Editor, see the WebSphere Studio Visual Editor documentation (see Resources).

And like many of the other projects under the Eclipse.org umbrella, including Eclipse, the stated goal of the Visual Editor project is quite ambitious: to build a tool for building graphical editing tools. While the initial release's support for AWT/Swing is complete, plans for Visual Editor go far beyond this. The technical underpinnings are being redesigned to be neutral with regard to the programming language and the graphical toolkit supported.

In the future, you will see Visual Editor implementations for toolkits other than AWT/Swing, such as SWT, and potentially, implementations for languages other than the Java™ programming language, such as C++. Work on adding SWT support is under way and will be included in Visual Editor V1.0, scheduled to be completed at around the same time as Eclipse V3.0, in mid-2004.


Under the Visual Editor hood

Visual Editor's first incarnation as a GUI builder for AWT/Swing is satisfying enough for GUI developers, but if you're the sort of developer who likes to pop the hood, there's lots to see: Visual Editor harnesses some interesting technologies that are useful on their own. If you are interested in building your own graphical editor or modeling tool, the existing Visual Editor implementation is only a hint of what you can accomplish.

The most obvious tool that Visual Editor draws upon is the Graphical Editing Framework (GEF). GEF builds upon the native Eclipse graphical toolkit, SWT, to make it easier to develop a graphical editor for diagrams or WYSIWYG text editors. If you are familiar with the graphics primitives in SWT (or AWT/Swing, which is similar in this regard), you know it's difficult to draw and manipulate arbitrary shapes such as rectangles, arrows, and ellipses, let alone manage the relationships between them and the data model that they represent.

GEF is divided into two parts: the Draw2D plug-in, which is a lightweight drawing and rendering package that helps you draw shapes and diagrams; and the GEF plug-in, which adds selection and creation tools, a tool palette, and a controller framework for mapping between data model and views.

GEF is a model-neutral framework. But as part of Visual Editor (and other graphical tools that generate code), it uses the Eclipse Modeling Framework (EMF) behind the scenes to map among a model (which is stored internally using XML metadata Interchange or XMI), a Java class, and the graphical representation. One of EMF's important features is that it ensures that these mappings are all 1:1. So while XMI might be considered the canonical representation of the model, nothing is lost when round-tripping from code to diagram. This is why Visual Editor only needs to save one representation of the model, the Java source code, and why you are free to edit this source code outside the graphical editor.

To learn more about GEF and EMF, see Resources.


Developing AWT/Swing applications with Visual Editor

As mentioned, release 0.5 is a complete AWT/Swing GUI builder. It works with Eclipse V2.1.x and compares favorably to the GUI builders available in other IDEs. For one thing, it generates high-quality code, comparable to what an experienced GUI developer would develop by hand, with no special artifacts that make modifications difficult. For another, its powerful parsing abilities allow full round-tripping of code, so changes made to the source code are reflected nearly immediately in the graphical editor.

One of the most tedious tasks in building a Swing application manually is managing the placement of components using layout managers. Because it's a WYSIWYG graphical editor, Visual Editor makes it easy to get the appearance and behavior you want in your user interface. Also, because it can map automatically between different layout managers, you can create your application's appearance using a null layout, which lets you get exactly the layout you want easily, then switch to a grid-bag layout, which allows the layout to behave well when the window is resized.

In the following sections, we'll take a quick look at Visual Editor V0.5 and some of its most interesting features. You'll need to have Eclipse V2.1.x installed together with Visual Editor V0.5. In addition, Visual Editor requires two other plug-ins: EMF and GEF (see Resources).


The Visual Editor tools

After installing Visual Editor, you'll find a few new features the next time you create a new Java project. Suppose you've created a project called VEPExample. If you right-click the project name in the Package Explorer and select New from the context menu, you'll see a new option for creating a Visual Class. Clicking this option will bring up a familiar dialog box with a new name, "Create a new Java Class using the Visual Editor." Another difference you'll notice are several radio buttons and a checkbox for selecting the superclass. Typically, you would create a JPanel to contain your application's UI elements, then add this panel to a JFrame. In the interest of brevity, you'll create a frame and add elements to it directly. For more information about developing Swing applications, see the series of tutorials listed in Resources.

Enter a name for the class, such as Test, and make sure that "frame" and "swing" are selected in the section labeled "Which visual class would you like to extend?" Also under "Which method stubs would you like to create?" select main().


Figure 1. Creating a new visual class
Creating a new visual class

After you make your selections, select Finish to create the visual class and open it using the Visual Editor. You'll notice that unlike the regular Java editor, the Visual Editor has three distinct sections. At the top is a graphical editor that shows what your visual class will look like when rendered at runtime. To the left is a list of widgets you can drag and drop onto your application. At the bottom is the source code.


Figure 2. Editing a Swing class with the Visual Editor
Editing a Swing class

You can see the interaction between the source and graphical views by scrolling through source and finding the initialize() method, which sets the initial size of the application window:

     private void initialize() {
            this.setSize(300, 200);
            this.setContentPane(getJContentPane());
     }

If you change the first number, the width, to a new value such as 600, you'll see that within a moment, the graphical representation above it will change width to reflect this new value. If you are making a lot of source code changes, you may wish to turn off synchronization by clicking the Stop Round Tripping button on the Eclipse status bar; otherwise, the editor may not be as responsive as you'd like.

In addition to the Visual Editor, you'll also notice two new views in your Java perspective: a JavaBeans view at the lower left and a Properties view at the upper right. As you may know, a design feature of Swing is that each component, such as the frame class you just created and any other widgets you add to it, is a JavaBean. The JavaBeans view allows you to navigate to these components in your class easily. Initially, the only entry below "this" (which refers to the class currently in the Visual Editor) is the jContentPanel. As you may know, you don't add things directly to a JFrame, but instead to its content panel. Clicking jContentPanel will take you to the getJContentPanel() method in the frame class.


Figure 3. The JavaBeans view
The JavaBeans view

The other view that the Visual Editor adds is the Properties view, which displays a JavaBeans' properties. Here, for example, after selecting jContentPane in the JavaBeans view, you can change the layout manager it uses. (Before you do, you may want to take a look at the source code in the Editor window to see that it sets the layout manager by calling jContentPane.setLayout() with a java.awt.BorderLayout object.) Some properties allow you to enter free text, but others provide a more appropriate interface; the property for the layout manages uses a drop-down list to limit you to valid layout managers. Click on the default value, BorderLayout, and then scroll up the list that appears to choose the null layout manager.


Figure 4. Selecting a null layout manager
Selecting a null layout manager.

After making this change, you'll see that in the source code, jContentPane.setLayout() is now called with a null value. To prove to yourself that the interaction between the Properties view and the Editor works both ways, you might try changing the null in the source code back to new java.awt.BorderLayout() and check that the value changes automatically in the Properties view.


Creating and enabling the UI

Once you've created a frame for your application, you can begin to add the widgets that allow the user to interact with your application. Let's add a checkbox that toggles a message on and off. Begin by clicking the JCheckbox widget and clicking inside the frame in the graphical editor. If you're using a null layout manager, you'll notice that you can place it anywhere within the content pane. If you're using the BorderLayout, you have the choice of placing it North, South, East, West, or Center.

Next, click the JLabel widget and click Next in the checkbox you added. Using the Properties view, change the text to "Unchecked" and adjust the size of the text box so the text fits properly. (Alternately, first expand the box, then click in the upper-left corner, which will open a text field where you can type the text.)

At this time, you can tidy up the widgets, if you like, by using the alignment tool. Select both by holding down Ctrl and clicking each in turn. Then click the Show Alignment Window button and the Align Top button.


Figure 5. Using the alignment tool to straighten things out
Using the alignment tool

Your frame should now look something like Figure 6.


Figure 6. A frame with two widgets
A frame with two widgets.

If you were to run this application at this point, not much would happen, of course. You'd be able to click the checkbox on and off because Swing takes care of that for you, but to have it actually do something, you'll need to add some code. If you are familiar with the Swing event model, you know that you need to add an action listener to the checkbox so that whenever the user changes it, the listener can perform some action. To add a listener using the Visual Editor, right-click the checkbox in the graphical editor and select Events > Action Performed from the context menu that appears. This will add the code for an action listener, implemented as an anonymous class, to the initialization code for the checkbox:

   private javax.swing.JCheckBox getJCheckBox() {
      if (jCheckBox == null) {
         jCheckBox = new javax.swing.JCheckBox();
         jCheckBox.setBounds(45, 75, 21, 21);
         jCheckBox
            .addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
               System.out.println("actionPerformed()");
               // TODO Auto-generated Event stub actionPerformed()
            }
         });
      }
      return jCheckBox;
   }

As you can see, where you need to add code with a TODO annotation is identified. Let's change the code so that whenever the checkbox changes, the label next to it changes, too, to reflect the checkbox's state. This is what the new code should look like after you make the change:

         jCheckBox
            .addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
               jLabel.setText(
                  jCheckBox.isSelected() ? "Checked" : "Unchecked");
            }
         });

It's time to test the application.


Running a visual class

Visual Editor conveniently lets you launch JavaBeans without the need for a main() class. This is especially convenient when you are testing a component such as a JPanel separate from the application that will eventually include it. To launch the simple test application you've created this way, make sure that Test.java is selected in the Editor, then select Run > Run As > Java Bean from the main Eclipse menu.

Alternatively, since this is a JFrame, you can also run Test as a Java application by completing the main() method as follows:

   public static void main(String[] args) {
      Test test = new Test();
      test.setDefaultCloseOperation(EXIT_ON_CLOSE);
      test.setVisible(true);
   }

Select Run > Run As > Java Application from the main menu to start it. Whichever way you run it, you should see that as you click the checkbox, the label changes correspondingly. If you haven't been following along in Eclipse, but want to see what the code looks like, you can download it (see Resources).


Sneak preview of Visual Editor V1.0 support for SWT

At the time of this writing, preliminary builds of Visual Editor V1.0 provide a preview of SWT support, although the final version is likely to be different. We'll take a quick peek here, but be aware that you may need to make adjustments if you are following along with a newer version.

When you download a nonrelease build of Visual Editor V1.0, such as the I20040325 integration build we are using here, you will also need to download the corresponding Eclipse, EMF, and GEF builds. These will not necessarily be release builds, and you cannot mix and match versions. The VEP download page (see Resources) will specify which builds are required and will contain links to them.

After installing Eclipse, Visual Editor, EMF, and GEF, start Eclipse and create a new Java project. To use SWT, you will need to add the SWT library to your project's Java build path. Right-click the project and select Properties > Java Build Path. Click on the Libraries tab, click the Add Library button, select Standard Widget Toolkit (SWT), then click Next. Accept the default "Use Platform SWT Level" in the next dialog and click Finish. Click OK to close the properties dialog box.

As before, create a new Visual Class by right-clicking the project and selecting New > Visual Class. Enter a name for the class, such as SWTTest. This time, however, instead of selecting "frame" as the visual class to extend, select "other." Also, make sure that the superclass is java.lang.Object and check the box next to the main() method under "Which method stubs would you like to create?"


Figure 7. Creating a SWT visual class
Creating a SWT visual class.

Initially, the graphical editor canvas will be empty. To create an application, you'll need to add an SWT Shell. You should find that the widget palette on the left of the Visual Editor contains a selection of SWT widgets (in addition to the AWT and Swing widgets). Click Shell, then click and drag on the canvas to create the application window.


Figure 8. Adding a SWT shell to the graphical editor
Adding a SWT shell to the graphical editor.

Now you can add widgets to the shell. Here we'll just add a single text field. Click Text, then click and drag in the shell to place it. Click in the top-left corner of the field to add some text, such as "Hello, SWT!"


Figure 9. Hello, SWT!
Hello, SWT!

After you've finished with these steps, you'll find that Visual Editor has created a method createSSHell(), which initializes the shell as follows:

   private void createSShell() {
      sShell = new org.eclipse.swt.widgets.Shell();
      text = new org.eclipse.swt.widgets.Text(sShell,
            org.eclipse.swt.SWT.NONE);
      sShell.setSize(new org.eclipse.swt.graphics.Point(209, 85));
      text.setBounds(new org.eclipse.swt.graphics.Rectangle(23,
            9, 153, 27));
      text.setText("Hello, SWT!");
   }

Next, we need to add some code to the main() method to instantiate the class and run the SWT code:

   public static void main(String[] args) {
      SWTTest test = new SWTTest();
      Display display = new Display();
      test.createSShell();
      test.sShell.open();
      while (!test.sShell.isDisposed()) {
         if (!display.readAndDispatch())
            display.sleep();
      }
      System.out.println("finishing...");
      display.dispose();
   }

After typing this in, you can right-click in the source window and select Source > Reorganize Imports to resolve the reference to Display.

To run the application, you need to add a platform-specific SWT shared library or DLL to your path. One way to do this is to use a launch configuration. Select Run > Run... from the Eclipse main menu, then click the Arguments tab in the dialog box that appears. In the VM arguments box, add a -D argument with a path to the libraries. In Windows®, if you've installed Eclipse in C:\eclipse, the complete argument will be -Djava.library.path=C:\eclipse\plugins\org.eclipse.swt.win32_3.0.0\os\win32\x86.


Figure 10. Adding a path to the Windows SWT DLLs to the launch configuration
Adding a path to the Windows SWT DLLs

After entering this argument, click Run to start the SWT application. If all has gone well, the application window will open with the message "Hello, SWT!"


Figure 11. The "Hello, SWT!" application window
Hello, SWT! application window


Summary

The Visual Editor Project adds the long-awaited GUI builder to Eclipse. The initial version, 0.5, contains support for AWT/Swing and puts Eclipse on even par with other IDEs with regard to GUI development. The next version, 1.0, will contain eagerly awaited support for SWT. Beyond that, nothing is certain, but because of its solid technological underpinnings, many things, including support for other programming languages and toolkits, are possible.



Download

NameSizeDownload method
os-ecvisual/test.zipHTTP

Information about download methods


Resources

Learn

Get products and technologies

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.

  • Participate in developerWorks blogs and get involved in the developerWorks community.

About the author

David Gallardo, a Studio B author, is an independent software consultant and author specializing in software internationalization, Java Web applications, and database development. He has been a professional software engineer for over fifteen years and has experience with many operating systems, programming languages, and network protocols. His recent experience includes leading database and internationalization development at a business-to-business e-commerce company, TradeAccess, Inc. Prior to that, he was a senior engineer in the International Product Development group at Lotus Development Corporation where he contributed to the development of a cross-platform library providing Unicode and international language support for Lotus products including Domino. David is co-author of Eclipse In Action: A Guide for Java Developers (Manning, 2003). He can be reached at david@gallardo.org.

Report abuse help

Report abuse

Thank you. This entry has been flagged for moderator attention.


Report abuse help

Report abuse

Report abuse submission failed. Please try again later.


developerWorks: Sign in


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


Rate this article

Comments

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Open source, Java technology
ArticleID=11910
ArticleTitle=Build GUIs with the Eclipse Visual Editor project
publish-date=03142006
author1-email=david@gallardo.org
author1-email-cc=