Monday, January 10, 2011

How to select file types in a File Chooser window (Java SWING)

The below tutorial explains how to select some particular file formats (like .jpg, .doc, .cer etc.) in the File Chooser window using Java SWING GUI. Detailed code snippets are interspersed along with the explanation.




First of all we need to have a JLabel, JTextField and JButton fields on the screen similar to the below screenshot. The JButton field is the button image with “…” text on it. Once you click the button, a popup window shows up to select the files (similar to the above screenshot). Whatever the User selects on the screen will be captured into the parent window’s JTextField (C:\Program Files\Common Files\Adobe\Updater6\AdobeUpdate.cer in the below example)


//JLabel:
JLabel certificatePath = new JLabel();
certificatePath.setText("Certificate Path");

//JTextField:
JTextField certificateDir = new JTextField(PropertyReader.get("certificateDir"));
certificateDir.setToolTipText("Location of the certificate file");

//JButton:
JButton browseCertificate = new JButton();
                                browseCertificate.setSize(24, 19);
                                browseCertificate.setPreferredSize(new java.awt.Dimension(24,19));
                                browseCertificate.setToolTipText("Browse and select the location of the cer file(ex: C:\\adobe.cer)");
                                browseCertificate.setText("...");
                                browseCertificate.addActionListener(new ActionListener() {
                                                public void actionPerformed(ActionEvent evt) {
                                                                browseCertificateActionPerformed(evt);
                                                }
                                });


In the above code, we added a listener that invokes a method on the click of the JButton. File selection filtering happens in the listener method.

I’m going to give a little explanation of the fields set in the listener method here. You can skip to the code directly if you just need a screen similar to the below image.

Java SWING provides a class called JFileChooser that allows us to set various properties on the ‘File Select’ popup.

  • The dialogTitle property shows the title on the popup window (“Select the certificate file” on the below screen)
  • The acceptAllFileFilterUsed Boolean is used to show the “All Files” value in the “Files of Type” dropdown. If the value is false, “All Files” option will not be shown.  (set to false on the below screen. Only *.cer value is shown)
  • The fileSelectionmode allows us to set the selection values to Files or Directories or both (set to Files only on the below screen)

To filter the files to show only some particular types of file Types, we create a new FileFilter class and override the two methods getDescription and accept.

  1. In the getDescription method, we return a String (something like “*.cer”). This value will be shown in the Files of Type dropdown.
  1. In the accept method, we write the logic to allow some particular file formats. For example, in the below code, we get the extension of the files using a utility method. If the extension equals “cer” we show it to the User. The important thing here is that we have to include the code if(f.isDirectory()){return true;} in the accept method. This will make sure that when we traverse across folders, we show the directories as well as the “cer” files. If we remove the isDirectory() block, we will not be able to traverse across folders.
Code snippets:
private void browseCertificateActionPerformed(ActionEvent evt) {

                JFileChooser fileChooser = new JFileChooser();
                fileChooser.setDialogTitle("Select the Certificate file");
                fileChooser.setAcceptAllFileFilterUsed(Boolean.FALSE);
                fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
               
                fileChooser.setFileFilter(new FileFilter() {
                                                @Override
                                                public String getDescription() {
                                                                return "*.cer";
                                                }
                                               
                                                @Override
                                                public boolean accept(File f) {
                                                                if (f.isDirectory()) {
                                                                                return true;
                                                                    }
                                                                String extension = getExtension(f);
                                                    if (extension != null) {
                                                                if (extension.equals("cer")) {
                                                                        return true;
                                                                } else {
                                                                    return false;
                                                                }
                                                    }

                                                    return false;
                                                }
                                });
               
                int selection = fileChooser.showDialog(null, "Select");
                if(selection == JFileChooser.APPROVE_OPTION) {
                                certificateDir.setText(fileChooser.getSelectedFile().getAbsolutePath());
                }

}//end of browseCertificateActionPerformed method

This is the utility method to find the extension of the file
/*
     * Get the extension of a file.
     */ 
    private static String getExtension(File f) {
        String ext = null;
        String s = f.getName();
        int i = s.lastIndexOf('.');

        if (i > 0 &&  i < s.length() - 1) {
            ext = s.substring(i+1).toLowerCase();
        }
        return ext;
    }

References/Links:
  1. http://download.oracle.com/javase/tutorial/uiswing/components/filechooser.html#filters


Tags: Java SWING File Chooser file formats types JFileChooser Basic tutorial popup running example code GUI

No comments :

Post a Comment