banner

JFileChooser and JColorChooser

Optional Reading

We will be using the Creating a GUI with JFC/Swing tutorial from Sun as a Reference source. You are not required to read the entire tutorial, I suggest you skim through it though to use a a supplement to what I give you here.

JColorChooser

JColorChooser is a component that displays some type of color chooser. There are convenience static methods to bring up a JColorChooser in a modal dialog window.

There are three modes of operation in Windows/Solaris environment.

In newer version of the JDK, linux JVMs may bring up a color chooser that looks differently than the Windows version.

JColorChooser practice

Download and open the Netbeans project jcolorchooser. If you run this application, you will get the following window. The screenshot below shows the initial window and the JColorChooser that comes up when you click on the Select Color button in the original window.

JColorChooser
JColorChooser

The only real gotcha in JColorChooser is that you have to check to see if the returned color from the code:

Color color = JColorChooser.showDialog ( this, "Select Color", Color.white );

Is not null. If the user selects the Cancel button in the JColorChooser, null is returned.;

JFileChooser

JFileChooser is another utility class that brings up a window that allows you to select a file(s) or directory. JFileChooser is another modal dialog window that blocks until you have chosen a file.

Warning: Be careful! Whenever you use a JFileChooser, the first thing you should do is check the return value from the method call. If the return value is CANCEL_OPTION, it means the user hit CANCEL. If the user selected a file, and then hit CANCEL, getSelectedFile() will still return the file selected, even though CANCEL was selected.

The code below will bring up a JFileChooser. It includes a FileNameExtensionFilter which allows the JFileChooser to filter out types of files, showing only the ones you want.

JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG & GIF Images", "jpg", "gif");
chooser.setFileFilter(filter);      
int returnVal = chooser.showOpenDialog(parent);      
if(returnVal == JFileChooser.APPROVE_OPTION) {         
    System.out.println("You chose to open this file: " +              
    chooser.getSelectedFile().getName());      
}

Download and open the Netbeans project filechooser. If you run the application, you should see the following:

JFileChooser

g src="../Images/filechooser.gif" alt="JFileChooser" width="595" height="405" />