Tutorial Tutorial Step 09

Building a Java text editor

Step 8: Adding a file chooser dialog

Let's hook up the File|Open menu item to an event handler that presents the user with a JFileChooser (file open dialog) for text files. If the user selects a file and clicks the OK button, then the event handler opens that text file and puts the text into the JTextArea.

  1. Switch back to the designer and select the JFileChooser component from the Swing Containers page of the palette.

  2. Click the UI folder in the component tree to drop the component. (If you click in the UI designer, the component will be dropped into the wrong section of the tree.)

  3. Select the File|Open menu item in the component tree (jMenuItem2).

  4. Create an actionPerformed() event and insert the following code:
    //Handle the File|Open menu item.
    // Use the OPEN version of the dialog, test return for Approve/Cancel
    if (JFileChooser.APPROVE_OPTION == jFileChooser1.showOpenDialog(this)) {
    
     // Display the name of the opened directory+file in the statusBar.
     statusBar.setText("Opened "+jFileChooser1.getSelectedFile().getPath());
    
     // Code will need to go here to actually load text
     // from file into TextArea.
    }
    

  5. Save and run the application. Using the File|Open menu, select a file and click OK. You should see the complete directory and file name displayed in the status line at the bottom of the window. However, no text appears in the text area. We'll take care of that in the next step.

  6. Close the "Text Editor" application before continuing.

Internationalizing Swing components

JBuilder Foundation users skip this step and go to Step 9.
If you are localizing your application, you need to add a line of code so the Swing components, JFileChooser and JColorChooser, will appear in the language the application is running in. Add the following line of code to the TextEditFrame class in TextEditFrame.java:
  IntlSwingSupport intlSwingSupport1 = new IntlSwingSupport();
Your code now looks like this:
public class TextEditFrame extends JFrame {
  IntlSwingSupport intlSwingSupport1 = new IntlSwingSupport();
  JPanel contentPane;
  JMenuBar menuBar1 = new JMenuBar();
  JMenu menuFile = new JMenu();
  ...
}

Note: When adding this line of code, you must also add the import statement import com.borland.dbswing.*; and the dbSwing library. In this tutorial, this was taken care of automatically when you added the dbSwing FontChooser component.

Now, when you run your application in other languages, the JFileChooser and JColorChooser will appear in the appropriate language.

See also: Internationalizing programs with JBuilder
"Adding and configuring libraries" in "Creating and managing projects"

Tutorial Tutorial Step 09