Tutorial: Building an application

This tutorial gets you up and running using the JBuilder integrated development environment (IDE). The tutorial shows how to:

For information on documentation conventions used in this tutorial, see "Documentation conventions."

For the complete source code, see the "HelloWorld source code" at the end of the tutorial.

For additional suggestions on improving this tutorial, send email to jpgpubs@inprise.com.


Overview Step 2

Step 1: Creating the project

First, you need a project in which to store your application. The Project wizard creates one for you:

  1. Choose File|New and double-click the Application icon in the object gallery.

    Object gallery

    The Project wizard opens first. After you complete this wizard, the Application wizard opens.

    Project wizard Step 1

  2. Make the following changes to the project and directory names in Step 1 of the Project wizard.

  3. Accept all other defaults. Note the root path where the project is saved.

    Note: Projects in JBuilder are saved by default in the /[home]/jbproject directory. It is recommended that only advanced users change this default path.

    For more information on projects, see "Creating and managing projects" in Building Applications with JBuilder.

  4. Click Next to go to Step 2 of the Project wizard.

    Project wizard Step 2

  5. Accept the defaults in Step 2 for the project, source, backup, and output paths and the JDK version. Note where the project, class, and source files will be saved. Also note that the option Make Project Notes File is checked. This option creates an HTML file that contains the project information entered in Step 3 of the wizard.

  6. Click Next to go to Step 3 of the wizard.

    Project wizard Step 3

  7. Make the following changes in the appropriate fields of Step 3:

  8. Click the Finish button.

    See also: "How JBuilder constructs paths" and "Where are my files?" in "Creating and managing projects" in Building Applications with JBuilder.

    Two files, HelloWorld.jpr and HelloWorld.html, appear in the project pane of the AppBrowser. The Application wizard is open on top of it.

    Application wizard


Overview Step 1 Step 3

Step 2: Generating your source files

The Application wizard creates .java files that are added to the project you just created.

To generate source files for your application, follow these steps:

  1. Accept the default package name, helloworld. By default, the wizard takes the package name from the project file name, HelloWorld.jpr.

  2. Enter HelloWorldClass in the Class field. This is a case-sensitive Java class name.

  3. Check Generate Header Comments. When you select this option, the information you entered in Step 3 of the Project wizard appears at the beginning of each source file that the Application wizard generates.

    Step 1 of the Application wizard should look like this:

  4. Click the Next button to go to Step 2 of the Application wizard.

  5. Type HelloWorldFrame in the Class field to name the Frame class.

  6. Type Hello World in the Title field. This text appears in the title bar of the frame in your application.

  7. Check all of the options for additional application features: Generate Menu Bar, Generate Toolbar, Generate Status Bar, Generate About Dialog, and Center Frame On Screen. The wizard generates the basic code to support these features.

    Step 2 of the Application wizard should look like this:

  8. Click the Finish button.

    The new .java class files and toolbar images are added to your project, and the source code for HelloWorldFrame.java is open in the content pane as shown in the image below.

    AppBrowser elements

  9. Choose File|Save All to save the source files and the project file.

    Note: The source files are saved to: /[home]/jbproject/HelloWorld/src/helloworld
    The class files are saved to: /[home]/jbproject/HelloWorld/classes/helloworld

Changing the project properties

Now, let's change one of the project properties for this project.
  1. Select Project|Project Properties and click the General tab.
  2. Uncheck the Enable Source Package Discovery And Compilation option. In most cases, it's best to leave this option on. For a description of this option, press the Help button on the General page of the Project Properties dialog box.

See also: "Setting project properties" in "Creating and managing projects" in Building Applications with JBuilder.


Overview Step 2 Step 4

Step 3: Compiling and running your application

Now, compile and run the application.

  1. Choose Run|Run Project Run icon  or click the Run button to compile and run your application.

    Tip: You can also select HelloWorldClass.java in the project pane, right-click, and select Run.

    Your application is displayed and should look like this:

    Note: The running application in this tutorial reflects the Windows Look & Feel.

  2. Choose File|Exit in the "Hello World" application to close it.

  3. Right-click the HelloWorldClass tab in the message pane at the bottom of the AppBrowser and select "Remove HelloWorldClass Tab" to close any compiler messages.


Overview Step 3 Step 5

Step 4: Customizing your application's user interface

Follow these steps to customize your application's user interface.

  1. Double-click HelloWorldFrame.java in the project pane if it's not already open.

  2. Click the Design tab to change to design view. The UI designer appears in the content pane with the Inspector on its right. You will use the Inspector to modify properties and add events to your code. The structure pane now contains a component tree containing components and such folders as UI, Menu, and Other.

    UI designer elements

  3. Click the Swing Containers tab on the component palette above the UI designer and select the JPanel component to add a panel to your design.

  4. Click the center of the frame in the UI designer to drop the component into the center of your design's frame.

    Note: The constraints property in the Inspector should be Center. If not, click the column to the right of the constraints property, and choose Center from the drop-down list.

    jPanel1 is now selected in your application design and in the component tree.

    Note: The component selected in the component tree or the UI designer displays in the status bar below the structure pane.

  5. Set the background color of jPanel1 to White.

    1. Click the column to the right of the background property in the Inspector.
    2. Click the Down arrow to open the color drop-down list and select White at the top of the list.

  6. Add a line border to jPanel1 and change the border color to Gray.

    1. Click the column to the right of the border property in the Inspector.
    2. Click the Down arrow to open the border drop-down list and select Line.
    3. Select the ellipsis button  to access the Border dialog box.
    4. Click Black under Options|Color to access the color drop-down list and select Gray.
    5. Click OK to close the Border dialog box.

  7. Change the layout manager for jPanel1 to null.

    1. Click the column to the right of the layout property in the Inspector.
    2. Choose null from the drop-down list.

    Important: Use null layout to prototype your design when laying out multiple components. Because null layout does not use a layout manager, you can place components exactly where you want them. Later, you can switch to an appropriate portable layout for your design. We recommend never leaving a container in null for deployment, because components do not adjust when you resize the parent container.


Overview Step 4 Step 6

Step 5: Adding a component to your application

Now you'll use the component palette to add a JLabel component to the JPanel component.

  1. Select the Swing tab on the component palette and click the JLabel component.

  2. Drop the component into your design's JPanel. Use one of the following two methods:

  3. Click the middle of the label component in the designer, and drag it to the center of the panel. Note that jLabel1 is added below jPanel1 in the component tree. If you drop the control in the wrong place, you can select jLabel1 in the component tree or in the designer and press the Del key. Then re-add it.

  4. Select jLabel1 in the component tree, and complete the following steps:

    1. Double-click the column to the right of the text property in the Inspector and type Hello World! Press Enter. "Hello World!" now appears in the label.
    2. Click the column to the right of the font property to set the font. Click the ellipsis button  to open the Font dialog box.
    3. Choose Serif from the list of fonts and check Bold and Italic. Enter 28 in the Size box, then click OK. Resize the jLabel1 by dragging the black handles until "Hello World" is visible.
    4. Click the column to the right of the foreground property in the Inspector to set the color of the "Hello World!" text. Click the Down arrow and select Blue from the drop-down list of colors.

    Your design now looks similar to this:

  5. Choose File|Save All.


Overview Step 5 Step 7 Source code

Step 6: Editing your source code

You can change information in the About box by directly editing the code. The default application version created by the Application wizard is 1.0.

  1. Double-click HelloWorldFrame_AboutBox.java in the project pane to open the file. The content pane changes to the source view where you can edit the code in the editor.

  2. Choose Search|Find. Type the following line of code in the Find/Replace Text dialog box:
    String version = "1.0"; 
    
  3. Click Find.

    The editor finds the selected text.

  4. Select 1.0 and enter 2.0 inside the quotes.

  5. Choose File|Save All.


Overview Step 6 Step 8

Step 7: Compiling and running your application

Now you can compile and run the application.

  1. Choose Project|Make Project.

  2. Choose Run|Run Project.

    The "Hello World" application is displayed:

  3. Choose Help|About. The version data you changed is now displayed in the About dialog box.

  4. Click OK to close the dialog box.

  5. Choose File|Exit in your "Hello World" application to close it.


Overview Step 7 Step 9

Step 8: Running your application from the command line

You can also run the application outside the JBuilder environment from the command line.

You can do this using any of these methods:

To run the application,

  1. Choose File|Close Project after compiling your project in JBuilder.

  2. Open the command-line window.

  3. Run the application with the following command on one line at the command prompt:

    java -classpath 
    /[home]/jbproject/HelloWorld/classes helloworld.HelloWorldClass

    Note: For Windows, use a backslash (\).

    This command should be in the following form:

    java -classpath package-name.main-class-name
    In this example,

See also: "Setting the classpath" and "Basic tools" at http://java.sun.com/j2se/1.3/docs/tooldocs/tools.html


Overview Step 8 Step 10 Source code

Step 9: Adding more components to your application

Next, you'll add another Swing component to your application.

  1. Reopen HelloWorld.jpr (File|Reopen). Open HelloWorldFrame.java and click the Design tab to switch to the UI designer.

  2. Click the JButton component  jButton  on the Swing tab of the component palette and drop it on either jPanel1 in the component tree or in the panel in your design. jButton4 is added below jPanel1 in the component tree.

  3. Click jButton4 in the design and drag it to the top center of the design as shown in the image below.

  4. Change the Text property in the Inspector from jButton4 to Push Me. Press Enter. Enlarge the button by dragging the black handles until "Push Me" shows completely.

    The Inspector should look like this:

  5. Click the Inspector's Events tab to define what happens when jButton4 is pressed.

  6. Double-click the column to the right of the ActionPerformed event.

    JBuilder switches to the editor where the following skeleton code has been added for the ActionPerformed event.

     
    void jButton4_actionPerformed(ActionEvent e) {
    
    }
      
    You can now enter code that defines the event.

  7. Type the following code indicated in bold:
     
    void jButton4_actionPerformed(ActionEvent e) {
      jLabel1.setForeground(new Color(255,0,0));
    }
      
    Tip: Use CodeInsight to complete the code for you. Type jLabel1. and wait for the pop-up window or press Ctrl+spacebar to invoke it. Type setfor to highlight setForeground(Color) from the pop-up window or use the arrow keys. Press Enter. You can configure CodeInsight in the IDE Options dialog box (Tools|IDE Options|CodeInsight).

    Now, when you run the application and push the "Push Me" button, "Hello World!" should turn red.

  8. Choose File|Save All.

  9. Choose Project|Make Project "hello.jpr."

  10. Choose Run|Run Project.

  11. Click the "Push Me" button. The color of the "Hello World!" text turns red.

  12. Choose File|Exit to close the "Hello World"application.

Steps 10 and 11 use features found in JBuilder Professional and Enterprise. If you are using JBuilder Foundation, you have completed the tutorial.


Overview Step 9 Step 11

Step 10: Preparing your application for deployment

Continue with the tutorial if you have JBuilder Professional or Enterprise.
The Archive Builder collects all the files needed to distribute your program, and if selected as the archive type, can archive them into a JAR file.

To deploy your application:

  1. Choose Wizards|Archive Builder to open the Archive Builder.

  2. Select Application from the Archive Type drop-down list.

  3. Click Next to go to Step 2.

  4. Accept the default name for the archive and default path for the JAR file. Note that HelloWorld.jar will be saved to the HelloWorld directory.

  5. Accept the defaults in Steps 3 through 6.

  6. Click Finish to close the Archive Builder. An archive node called Application appears in the project pane. You can modify this file by right-clicking and selecting Properties.

  7. Select Project|Make Project to compile your application and create the JAR file. The Archive Builder gathers all the files in the project's output path (Project|Project Properties|Paths) into the JAR file.

  8. Expand the  icon next to the Application archive node to see the HelloWorld.jar archive file. Double-click the JAR file in the project pane. The manifest file appears in the content pane and the contents of the JAR file appear in the structure pane.

    Archive viewer

For more information on deployment, see "Deploying Java programs" in Building Applications with JBuilder.


Overview Step 10

Step 11: Running your deployed application from the command line

Continue with the tutorial if you have JBuilder Professional or Enterprise.

To test the deployed application, you can run the JAR file from the command line.

Note: The jdk/bin directory must be on your path or you must run the application from within the jdk/bin directory.

  1. Open the command-line window.

  2. Enter the following command on one line at the prompt:

    java -classpath /[home]/jbproject/HelloWorld/HelloWorld.jar helloworld.HelloWorldClass

    Note: For Windows, use a backslash (\).

    The command must have the following form:

    java -classpath package-name.main-class-name

    For information on JAR files, see the JAR tutorial at http://java.sun.com/docs/books/tutorial/jar/index.html.

  3. The "Hello World" application loads and runs.

Congratulations, you've created your first application with JBuilder. Now that you're familiar with JBuilder's development environment, you'll find its many time-saving features make your programming easier.



Overview Step 6 Step 9

HelloWorld source code

Select a link to view the code:

Source code for HelloWorldFrame.java

/**
 * Title:        HelloWorld
 * Description:  This is the "Hello World" tutorial.
 * Copyright:    Copyright (c) 2000
 * Company:      MyCompany
 * @author MyName
 * @version 1.0
 */

package helloworld;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class HelloWorldFrame extends JFrame {
  JPanel contentPane;
  JMenuBar jMenuBar1 = new JMenuBar();
  JMenu jMenuFile = new JMenu();
  JMenuItem jMenuFileExit = new JMenuItem();
  JMenu jMenuHelp = new JMenu();
  JMenuItem jMenuHelpAbout = new JMenuItem();
  JToolBar jToolBar = new JToolBar();
  JButton jButton1 = new JButton();
  JButton jButton2 = new JButton();
  JButton jButton3 = new JButton();
  ImageIcon image1;
  ImageIcon image2;
  ImageIcon image3;
  JLabel statusBar = new JLabel();
  BorderLayout borderLayout1 = new BorderLayout();
  JPanel jPanel1 = new JPanel();
  Border border1;
  JLabel jLabel1 = new JLabel();
  JButton jButton4 = new JButton();
  /**Construct the frame*/
  public HelloWorldFrame() {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {
      jbInit();
    }
    catch(Exception e) {
      e.printStackTrace();
    }
  }

  /**Component initialization*/
  private void jbInit() throws Exception  {
    image1 = new ImageIcon(helloworld.HelloWorldFrame.class.getResource("openFile.gif"));
    image2 = new ImageIcon(helloworld.HelloWorldFrame.class.getResource("closeFile.gif"));
    image3 = new ImageIcon(helloworld.HelloWorldFrame.class.getResource("help.gif"));
    //setIconImage(Toolkit.getDefaultToolkit().createImage(HelloWorldFrame.class.getResource("[Your Icon]")));
    contentPane = (JPanel) this.getContentPane();
    border1 = BorderFactory.createLineBorder(Color.gray,1);
    contentPane.setLayout(borderLayout1);
    this.setSize(new Dimension(400, 300));
    this.setTitle("Hello World");
    statusBar.setText(" ");
    jMenuFile.setText("File");
    jMenuFileExit.setText("Exit");
    jMenuFileExit.addActionListener(new ActionListener()  {

      public void actionPerformed(ActionEvent e) {
        jMenuFileExit_actionPerformed(e);
      }
    });
    jMenuHelp.setText("Help");
    jMenuHelpAbout.setText("About");
    jMenuHelpAbout.addActionListener(new ActionListener()  {

      public void actionPerformed(ActionEvent e) {
        jMenuHelpAbout_actionPerformed(e);
      }
    });
    jButton1.setIcon(image1);
    jButton1.setToolTipText("Open File");
    jButton2.setIcon(image2);
    jButton2.setToolTipText("Close File");
    jButton3.setIcon(image3);
    jButton3.setToolTipText("Help");
    jPanel1.setBackground(Color.white);
    jPanel1.setBorder(border1);
    jPanel1.setLayout(null);
    jLabel1.setFont(new java.awt.Font("Serif", 3, 28));
    jLabel1.setForeground(Color.blue);
    jLabel1.setText("Hello World!");
    jLabel1.setBounds(new Rectangle(135, 111, 184, 56));
    jButton4.setText("Push Me");
    jButton4.setBounds(new Rectangle(157, 21, 117, 36));
    jButton4.addActionListener(new java.awt.event.ActionListener() {

      public void actionPerformed(ActionEvent e) {
        jButton4_actionPerformed(e);
      }
    });
    jToolBar.add(jButton1);
    jToolBar.add(jButton2);
    jToolBar.add(jButton3);
    jMenuFile.add(jMenuFileExit);
    jMenuHelp.add(jMenuHelpAbout);
    jMenuBar1.add(jMenuFile);
    jMenuBar1.add(jMenuHelp);
    this.setJMenuBar(jMenuBar1);
    contentPane.add(jToolBar, BorderLayout.NORTH);
    contentPane.add(statusBar, BorderLayout.SOUTH);
    contentPane.add(jPanel1, BorderLayout.CENTER);
    jPanel1.add(jLabel1, null);
    jPanel1.add(jButton4, null);
  }

  /**File | Exit action performed*/
  public void jMenuFileExit_actionPerformed(ActionEvent e) {
    System.exit(0);
  }
jLabel1.setf
  /**Help | About action performed*/
  public void jMenuHelpAbout_actionPerformed(ActionEvent e) {
    HelloWorldFrame_AboutBox dlg = new HelloWorldFrame_AboutBox(this);
    Dimension dlgSize = dlg.getPreferredSize();
    Dimension frmSize = getSize();
    Point loc = getLocation();
    dlg.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y);
    dlg.setModal(true);
    dlg.show();
  }

  /**Overridden so we can exit when window is closed*/
  protected void processWindowEvent(WindowEvent e) {
    super.processWindowEvent(e);
    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
      jMenuFileExit_actionPerformed(null);
    }
  }

  void jButton4_actionPerformed(ActionEvent e) {
    jLabel1.setForeground(new Color(255,0,0));
  }
}

Source code for HelloWorldClass.java

/**
 * Title:        HelloWorld
 * Description:  This is the  "Hello World" tutorial.
 * Copyright:    Copyright (c) 2000
 * Company:      MyCompany
 * @author MyName
 * @version 1.0
 */

package helloworld;

import javax.swing.UIManager;
import java.awt.*;

public class HelloWorldClass {
  boolean packFrame = false;

  /**Construct the application*/
  public HelloWorldClass() {
    HelloWorldFrame frame = new HelloWorldFrame();
    //Validate frames that have preset sizes
    //Pack frames that have useful preferred size info, e.g. from their layout
    if (packFrame) {
      frame.pack();
    }
    else {
      frame.validate();
    }
    //Center the window
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    Dimension frameSize = frame.getSize();
    if (frameSize.height > screenSize.height) {
      frameSize.height = screenSize.height;
    }
    if (frameSize.width > screenSize.width) {
      frameSize.width = screenSize.width;
    }
    frame.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
    frame.setVisible(true);
  }

  /**Main method*/
  public static void main(String[] args) {
    try {
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    }
    catch(Exception e) {
      e.printStackTrace();
    }
    new HelloWorldClass();
  }
}