Java Technology Home Page
A-Z Index

Java Developer Connection(SM)
Technical Tips

Downloads, APIs, Documentation
Java Developer Connection
Tutorials, Tech Articles, Training
Online Support
Community Discussion
News & Events from Everywhere
Products from Everywhere
How Java Technology is Used Worldwide
Print Button
 
Tech Tips archive

Tech Tips
June 15, 1999

This issue presents tips, techniques, and sample code for the following topics:

File Choosers

JFileChooser is a class found in JavaTM Foundation Classes (JFC) Project Swing that allows a user to select a file. You might use a file chooser in an application in which the user selects the target file for an operation. A word processing program is a good example of this type of application.

Typically, you display a file chooser in response to some user action, such as when a user clicks a button. The user must select a file or cancel the request before doing anything else. This type of interaction is known as a modal interaction, and it's the way the Java 1.1 FileDialog class works. JFileChooser also supports non-modal interactions. In this case, the chooser is always on display and an action listener processes selection events.

Here is an example that illustrates the non-modal style of interaction. The example implements a browser for image files (GIF, JPG, JPEG):

  
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.io.File;

// filter for gif/jpg/jpeg files
class ImageFileFilter extends FileFilter {
// return true if should accept a given file
  public boolean accept(File f) {
    if (f.isDirectory())
      return true;
    String path = f.getPath().toLowerCase();
    if (path.endsWith(".gif"))
      return true;
    if (path.endsWith(".jpg"))
      return true;
    if (path.endsWith(".jpeg"))
      return true;
    return false;
  }
// return a description of files
  public String getDescription() {
    return "Image file (*.gif,*.jpg,*.jpeg)";
  }
}

public class chooser {
  public static void main(String args[]) {
    JFrame frame = new JFrame("File Chooser demo");
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });

// label to attach image icon to
    final JLabel label =
      new JLabel("", SwingConstants.CENTER);

    JPanel panel1 = new JPanel();
// start filechooser in current directory
    String cwd = System.getProperty("user.dir");
    final JFileChooser fc = new JFileChooser(cwd);
    fc.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
// set label's icon to the current image
        String state =
          (String)e.getActionCommand();
        if (!state.equals(
          JFileChooser.APPROVE_SELECTION))
          return;
        File f = fc.getSelectedFile();
        if (f == null || !f.isFile())
          return;
        ImageIcon icon =
          new ImageIcon(f.getPath());
        label.setIcon(icon);
      }
    });
// set the file filter for the filechooser
    fc.setFileFilter(new ImageFileFilter());
    panel1.add(fc);

    JPanel panel2 = new JPanel();
// max size of label whose icon displays image
    label.setPreferredSize(new Dimension(500, 300));
    panel2.add(label);

    frame.getContentPane().add("North", panel1);
    frame.getContentPane().add("South", panel2);
    frame.pack();
    frame.setVisible(true);
  }
}
Because it's non-modal, the file chooser doesn't pop up in response to some user request, and it doesn't require an immediate response. In other words, the file chooser is always there. If a user selects a file name, the image file is immediately displayed.

The file chooser is initialized to start in the current directory. Then an instance of ImageFileFilter is set to filter files, allowing only files through with extensions of .gif, .jpg, and .jpeg.

The action listener for the file chooser is called when the user single clicks a file and selects Open, or when the user double clicks a file. Selecting a file doesn't actually open or save the file. It simply triggers an action event, so that the application can retrieve the name of the selected file, and operate on it as desired.

The image is displayed by creating an ImageIcon object, then setting the icon for a JLabel object. The image is centered in the label field, and clipped if it's too large. An alternative would be to scale the image to fit in the allotted space, using Image.getScaledInstance.

JFileChooser also supports custom file views, via the FileView class. These customized views are useful if you want to display icons associated with the filenames in the file chooser list. The icons indicate the file type.

Using the Graphics Environment Class

GraphicsEnvironment is an abstract class that is new in the Java 2 platform . It is used to describe the collection of available graphics device objects (such as screens and printers) and fonts available on a given Java platform. An application can query this information as a way to configure itself.

To see how this works in practice, here is a short example:

  
import java.awt.*;

public class fontlist {
  public static void main(String args[]) {
    GraphicsEnvironment env =
      GraphicsEnvironment.
      getLocalGraphicsEnvironment();

    String list[] = env.getAvailableFontFamilyNames();

    for (int i = 0; i < list.length; i++)
      System.out.println(list[i]);
  }
}
The static method getLocalGraphicsEnvironment is called to obtain an instance of the GraphicsEnvironment class. If you insert a statement such as:
  
System.out.println(env);
immediately after obtaining the instance, the output is something like this:
  
sun.awt.Win32GraphicsEnvironment@7efa4213
This indicates that an internal class "Win32GraphicsEnvironment" is used to implement the abstract class on a particular platform (in this case, Win32 on NT 4.0).

The environment is then used to get a list of all the available font names, which are printed. The output looks something like this:

  Arial
  Arial Black
  Arial Narrow
  Bookman Old Style
  Comic Sans MS
  Courier New
  Default
  Dialog
  ...
This graphics environment sequence replaces an older one:
  
String list[] = 
    Toolkit.getDefaultToolkit().getFontList();
which has been deprecated.

The Java Developer ConnectionSM Tech Tips are written by Glen McCluskey.


Print Button
[ This page was updated: 21-Sep-2000 ]
Products & APIs | Developer Connection | Docs & Training | Online Support
Community Discussion | Industry News | Solutions Marketplace | Case Studies
Glossary | Feedback | A-Z Index
For more information on Java technology
and other software from Sun Microsystems, call:
(800) 786-7638
Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.
Sun Microsystems, Inc.
Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.