`
java-mans
  • 浏览: 11434647 次
文章分类
社区版块
存档分类
最新评论

Build GUIs with the Eclipse Visual Editor project

 
阅读更多
Build GUIs with the Eclipse Visual Editor project

<name>David Gallardo</name> (david@gallardo.org)
Software consultant
04 May 2004


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 or 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 graphical user interfaces. Happily, this was remedied by the November 2003 launch of the Eclipse Visual Editor Project and the release soon after of Visual Editor 0.5, which allows you to create AWT/Swing applications with a complete WYSIWYG (what you see is what you get) graphical editor.

Like Eclipse itself, Visual Editor is based on a code contribution by IBM. Developers familiar with the Visual Editor in WebSphere Studio Application Developer 5.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 listed in the Resources section at the end of this article.

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 language, such as C++. Work on adding SWT support is already underway, in fact, and will be included in Visual Editor release 1.0, which is scheduled to be completed at around the same time as Eclipse 3.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 open the hood, there's lots to see: Visual Editor harnesses some very 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 GEF, the Graphical Editing Framework. 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 that it is 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 first part is the Draw2D plug-in, which is a lightweight drawing and rendering package that helps you draw shapes and diagrams. The second part is the GEF plug-in, which adds (among other things) 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 one-to-one; so while XMI might be considered the canonical representation of the model, nothing is lost when round-tripping from code to diagram and back. This is why Visual Editor only needs to save one representation of the model, the Java source code, and why developers are free to edit this source code outside the graphical editor.

To learn more about GEF and EMF, see the links in this article's Resources section.

Developing AWT/Swing applications with Visual Editor
As mentioned, release 0.5, available now, is a complete AWT/Swing GUI builder. It works with Eclipse 2.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, and then switch to a grid-bag layout, which allows the layout to behave well when the window is re-sized.

In the following sections, we'll take a quick look at Visual Editor 0.5 and some of its most interesting features. If you want to follow along, you'll need to have Eclipse 2.1.x installed together with Visual Editor 0.5. In addition, Visual Editor requires two other plug-ins, EMF and GEF. See the Resources section for download links and installation information.

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 and then add this panel to a JFrame. In the interest of brevity, here you'll create a frame and add elements to it directly. For more information on developing Swing applications, see the series of tutorials listed in the Resources section.

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() (see Figure 1 below).

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

After you make your selections, press 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 run-time. To the left is a list of widgets that you can drag and drop onto your application. At the bottom is the source code (see Figure 2).

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 down 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 Java Beans view at the lower left and a Properties view at the upper right. As you may know, one of the design features of Swing is that each component, such as the frame class that you just created and any other widgets that you add to it, is a Java Bean. The Java Beans 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 (see Figure 3).

Figure 3. The Java Beans view
The Java Beans view

The other view that the Visual Editor adds is the Properties view, which displays a Java Beans' 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 (see Figure 4).

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. If you want 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 user interface
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 then 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 previously. Using the Properties view, change the text to "Unchecked" and then adjust the size of the text box so that the text fits properly. (Or alternately, first expand the box and then click in the upper left corner; this 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 the Control key and clicking each in turn. Then click the Show Alignment Window button and the Align Top button, as shown in Figure 5.

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 Java Beans 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 and 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 using the link provided in Resources.

Sneak preview of Visual Editor 1.0 support for SWT
At the time of this writing, preliminary builds of Visual Editor 1.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 non-release build of Visual Editor 1.0, such as the I20040325 integration build that we are using here, you will also need to download the corresponding Eclipse, EMF, and GEF builds. These will not necessarily be release builds either, and you can not 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), and 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?" (see Figure 7).

Figure 7. Creating an SWT visual class
Creating an 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, and then click and drag on the canvas to create the application window (see Figure 8).

Figure 8. Adding an SWT shell to the graphical editor
Adding an 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 and 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'll need to add some code to the main() method in order 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'll 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, and 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. See Figure 10.

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!" as seen in Figure 11.

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, is due soon and 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.

Resources

Download
<nbsp></nbsp> Name <nbsp></nbsp> <nbsp></nbsp> Size <nbsp></nbsp> <nbsp></nbsp> Download method <nbsp></nbsp>
<nbsp></nbsp> os-ecvisual/test.zip <nbsp></nbsp> <nbsp></nbsp> <nbsp></nbsp> <nbsp></nbsp> FTP <nbsp></nbsp>
*Information about download methods
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.
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics