Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

JVM Languages

The Eclipse Visual Editor for Java


October, 2004: The Eclipse Visual Editor for Java

Michael is a software engineer and researcher for the Department of Defense at the Naval Research Laboratory. Michael also founded and operates as CTO of Zizworks (http://www.zizworks.com/), a web-application and software-development company.


Picasso and Rembrandt conceived a visual idea and expressed it one brush stroke at a time until masterpieces for the ages stood on the easel. Today, many software engineers try to "paint" graphical user interfaces (GUIs) by writing line after line of code. However, modern tools are available to help you quickly produce high-quality GUI masterpieces, even if you're not a GUI expert.

In use since the late 1980s, visual editors (sometimes called "GUI builders") encompass a collection of software tools that help you in quickly creating attractive and usable interfaces for your application. Visual editors can be found for almost any programming language—including Java, which supports the Advanced Windowing Toolkit (AWT) and the more widely used Swing GUI libraries. However, as anyone who has worked with Swing will attest, it is flexible but can be difficult to work with.

Java GUI development normally consists of writing hundreds of lines of code using the Swing and AWT libraries, compiling, running, then tweaking for many hours to get the interface to look and behave just right. This cycle of coding, running, coding, running can be time consuming and frustrating. In some cases, it can even delay a project or cause shortcuts to be taken by weary developers leading to unusable GUIs. Enter the visual editor. Visual editing lets you drag-and-drop GUI components onto a visual display of the final GUI, creating a complete "what you see is what you get" (WYSIWYG) tool. Using a visual editor can cut a tremendous amount of tedious coding out of the interface development cycle.

To that end, the Eclipse Project has released Visual Editor for Java—a plug-in for visual editing. The Eclipse visual editor has some nice features, some of which have never been seen before in visual editing tools. In this article, I take you through the steps to create a simple application using the Visual Editor plug-in. You will see just how simply and quickly cross-platform graphical applications can be developed using a visual editor tool.

Installation

The first step in using the Visual Editor plug-in is to install Eclipse and the required plug-ins (http://www.eclipse.org/). Follow the download link to find a version for your platform and follow the instructions on the site to install it. For most platforms, this just requires extracting the package you download. Although it is not obviously stated on the Visual Editor web site, the plug-in does have a dependency on a specific Eclipse version, so be sure to read the site and download the correct one.

You need to install the Visual Editor plug-in after Eclipse is installed and working. Currently, the Visual Editor for Java plug-in has two dependencies that can be found at http://www.eclipse.org/vep/. Follow the instructions on the site to install them, which primarily consists of extracting the plug-ins into the proper directories in the Eclipse folder.

Hello GUI World

For the purposes of illustration, your first application using the Visual Editor is a simple interface that lets you get a feel for the components of the tool. The application is a window with a label, using the default layout (I'll explain more about layouts later). To start, run Eclipse and create a new Java project File| New|Project, select Java Project as the type of project and name it "HelloGUIWorld." The new project should now appear in the tree view of the Java perspective. If you don't see the Java perspective, open it using the Open Perspective button on the upper right-hand corner of the window.

Creating a new visual class in the project is similar to creating any other class in the Eclipse IDE, so these steps will be familiar if you've used Eclipse before. Right click on the HelloWorldGUI project and select New|Other... to display the New dialog. Click the Show All Wizards checkbox to show all the wizards and expand the Java node in the tree. You should now see that the Visual Editor plug-in has placed a Visual Class option in the list, similar to Figure 1. Select Visual Class and click the Next button.

The dialog is replaced with the New Class dialog. This dialog allows you to enter the name of the class as well as the base class that your new class will extend. Type in "MyFrame" as the name of the class and click the public static void main(String[] args) checkbox. Leave the rest of the values in their defaults so the values match Figure 2 and click the Finish button. Eclipse creates the new class and displays it using the Visual Editor as shown in Figure 3. The editor is split into two parts, the WYSIWYG panel at the top and the normal code editor at the bottom. As you edit the GUI in the top panel, you can instantly watch the code get generated (see Listing One) and changed in the bottom panel.

By using the defaults in the New Class dialog, Eclipse created a new class that extends JFrame, the basic window class in Swing. With the editor open, you need to add the label and button to the visualized frame in the top panel. Simply left click the JLabel in the Swing components list on the left and move your mouse over the JFrame. As you move your mouse around the frame, you will see the Visual Editor telling you what part of the layout will be filled with the new label if you were to click in that location. The default layout of a JFrame is a BorderLayout, which means the main component should go into the Center location in the layout. Move your mouse over the frame until Center appears and left click. The frame updates with the label in the center. Looking at the code in the lower editor, you can see that a new method getJLabel() has been created automatically.

Of course, you don't want all of your labels to have the same text, so you need to change the text by modifying the label. The Visual Editor plug-in lets you change many properties of a component by using the JavaBeans browser and Property Editor, two views added by the plug-in. Below the code editor (although, the location may vary with Eclipse versions), Eclipse displays tabs for each of these tools. Click on the JavaBeans browser to raise it to the top. This tool displays the beans in the interface you are editing. Swing components follow the JavaBean specification to expose properties that you can edit on the component. You can see that the frame you're editing appears, with the label as a child. Select the label from this tree, and then click on the Property Editor tab. The Property Editor tool displays all of the properties of the selected bean (just the label in this case) and allows you to change these properties. Since you want to change the text of the label, scroll through the list to find the text property. Click in the value column to select the current text and change it to read "Hello World. My First GUI Application!" and press Enter. You will see both the frame update in the upper panel and the code update in the lower panel as in Figure 4. Although there are numerous properties for the beans, you'll find that you only commonly edit the same few. Most of the properties are documented in the normal Javadoc documentation (look at the set* and get* methods).

It's time to run your new application and see the fruits of your labor. When you created the class, you asked that Eclipse provide a main method stub for you. Scroll in the code editor to find the method and edit it to read:

public static void main(String[] args) {
MyFrame f = new MyFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.show();
}

Run the application by clicking Run|Run As|Java Application. You now have a running GUI application without having to write a single line of GUI code! Click on the "x" in the corner to close the window and exit the application.

Make It Interactive

Although the last application was incredibly impressive, you probably want more. In this section, I walk you through adding a button and making the interface a little more interactive. Adding the button is no different than adding the label. Click on the JButton on the left and move the mouse over the frame in the editor panel. This time, however, you are going to add the button to the south compartment of the layout. You will notice that the Visual Editor automatically disables the center compartment because you used that earlier for the label. Move your mouse over the bottom of the frame until the south compartment is selected and left click to place the button. By default, buttons have no text, causing the component to be very small (because the layout is squashing it). Because a button without text would not be very user friendly, add text to yours using the Property Editor in the same fashion as before with the label. Set the text to "Push Me" and watch it update in the Visual Editor and the code editor.

With the button on the frame, it needs to react to the user clicking on it. Whenever a JButton is clicked, it will notify all ActionListeners of the event; therefore, you need to add one. The Visual Editor lets you add action listeners by right clicking on the button in the frame, and selecting Events|Action Performed. In the lower code editor, you see that a new anonymous ActionListener instance is created and added to the button as an action listener. Let's assume that whenever the button is clicked, you want to update the text in your label. Create a counter field in the MyFrame class by placing the line:

private int counter = 0;

at the top of the class with the other field declarations. In the new ActionListener actionPerformed(...) method, add the following code:

++counter;
getJLabel().setText("The button was clicked " +
counter + " times.");

This code is executed every time the button is clicked, incrementing the counter and updating the text in the label. Run the application just like last time. Presto, you just created an interactive GUI application with no fuss.

Laying It All Out

As mentioned, the Visual Editor plug-in does support Swing layouts. This is a tremendously useful feature since most Swing layouts can be difficult to work with and visualize, especially if you are new to Swing. Although complete coverage of Swing layouts is beyond the scope of this article, it is important to mention a few key facts. All of the popular layouts are supported, including: null (or static layout), BoxLayout, BorderLayout, GridLayout, FlowLayout, CardLayout, and the (in)famous GridBagLayout. Layouts are defined as properties of the container bean and global layout properties (such as vertical gap) are expressed as subproperties of the layout. Component-specific properties (such as constraints for a given component) are expressed as properties of the respective component. Like any other property of a bean, the layout can be changed in the editor and the GUI will update to represent the change. The best way to learn how layouts work in the editor is to experiment around with them in a simple application.

Round Trippin'

Although visual editing is an efficient and easy-to-learn technique, there may be a time when you feel that you could just do what you want by editing code faster than with the tool. Until recently, many GUI builders forced you to accept that any graphical interface code had to be generated by the tool. If you edited the code directly, the tool would not properly apply the changes in the best case, or stop functioning all together in the worst case. The Eclipse Visual Editor avoids these problems by implementing true round-trip engineering. The documentation defines round-trip engineering as, "In the design window, JavaBeans that are AWT or Swing widgets are shown graphically. As you modify the JavaBeans in the design window, the source is updated. Conversely, as you change the source files, the design window is updated to reflect the changes you make." With this powerful feature, you can choose which pieces are faster to do with the visual editor and which pieces you can implement faster in code alone.

For instance, you already saw how editing using the upper visual editor changes code by adding new methods and updating the GUI components. Using the same HelloGUIWorld project from the previous sections, you will see how editing the code updates the visual editor. Start by scrolling through the lower code editor to find the method initialize(), which is used to initialize your JFrame when it is created. This method was generated by the visual editor when you first created the JFrame application. In the code editor, modify the method by adding the line:

this.setTitle("Click Counter");

to set the title of the JFrame in the application. Instantly, the GUI should update in the upper visual editor to reflect the change. Confirm that the change was applied by selecting "this" (the default reference to the JFrame) in the JavaBean browser and using the Properties Editor to look at the title property, as in Figure 5. Although just a simple change, it represents how the code will be modified based on changes in the visual editor, and how the visual editor will update to reflect changes in the code. This feature makes the Eclipse Visual Editor stand out as a very powerful tool.

Conclusion

The simple HelloGUIWorld that you wrote is a small example of what is possible with the Eclipse Visual Editor plug-in. Aside from the rapid development and reduced test, fix, test cycles, visual editors can also be used to allow nonprogrammers to design application interfaces. In a team environment, a human computer interaction (HCI) group could quickly prototype and test GUIs and then hand working code off to the programming team to actually implement. The Visual Editor for Java plug-in is a new contender in the field; however, with features such as layout management, a simple and easy to learn interface, round-trip engineering, and Eclipse IDE integration, it is sure to make an impact. Although not required in the example application, the Visual Editor developers have stated that they intend on moving the Visual Editor into a multilanguage, multitoolkit editor. In the future, the same tool could be used to produce C++ code, as well as Java code using Swing, AWT, and SWT.

DDJ



Listing One

import javax.swing.JFrame;
/**
 * A simple JFrame-based application to show the basics of using the Visual
 * Editor for Java Eclipse plugin. The frame contains a label and a button.
 */
public class MyFrame extends JFrame {

  /**
   * The counter field that tracks the number of times the button was clicked.
   */
  private int counter = 0;

  /**
   * The content pane of the JFrame. This was generated by the Visual Editor.
   */
  private javax.swing.JPanel jContentPane = null;

  /**
   * The label displayed in the frame. Generated by the Visual Editor.
   */
  private javax.swing.JLabel jLabel = null;

  /**
   * The button displayed in the frame. Generated by the Visual Editor.
   */
  private javax.swing.JButton jButton = null;

  /**
   * The main method. The stub was generated by the new class wizard, and
   * then implemented to simply display the frame.
   * param args
   *          command line arguments, ignored
   */
  public static void main(String[] args) {
    MyFrame f = new MyFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.show();
  }
  /**
   * Constructs the frame by initializing the content.
   */
  public MyFrame() {
    super();
    initialize();
  }
  /**
   * Initializes the content of the frame and sets the title. The default
   * implementation was generated by the Visual Editor, although it was
   * customized to provide a title.
   */
  private void initialize() {
    this.setSize(300, 200);
    this.setContentPane(getJContentPane());
    this.setTitle("Click Counter");
  }
  /**
   * Returns the content pane for this frame. This code was generated by
   * the Visual Editor.
   * return the content pane for this frame
   */
  private javax.swing.JPanel getJContentPane() {
    if (jContentPane == null) {
      jContentPane = new javax.swing.JPanel();
      jContentPane.setLayout(new java.awt.BorderLayout());
      jContentPane.add(getJLabel(), java.awt.BorderLayout.CENTER);
      jContentPane.add(getJButton(), java.awt.BorderLayout.SOUTH);
    }
    return jContentPane;
  }
  /**
   * Returns label for this frame. Code was generated by the Visual Editor.
   * return the label for this frame
   */
  private javax.swing.JLabel getJLabel() {
    if (jLabel == null) {
      jLabel = new javax.swing.JLabel();
      jLabel.setText("Hello World. My First GUI Application!");
    }
    return jLabel;
  }
  /**
   * Returns the button for this frame. Generated by the Visual Editor.
   * return the button for this frame
   */
  private javax.swing.JButton getJButton() {
    if (jButton == null) {
      jButton = new javax.swing.JButton();
      jButton.setText("Push Me");
      jButton.addActionListener(new java.awt.event.ActionListener() {

        public void actionPerformed(java.awt.event.ActionEvent e) {
          ++counter;
          getJLabel().setText("The button was clicked "+ counter +" times.");
        }
      });
    }
    return jButton;
  }
}
Back to article


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.