Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Java Note Swing - 8: File Chooser and Color Chooser Dialogs 1 2 Purpose ................................................................................1 JFileChooser dialogs .................................................................1 2.1 Basic operation ..................................................................1 2.2 Example ..........................................................................2 2.3 Changing the initial directory .................................................5 2.4 Setting the dialog title .........................................................5 2.5 Enabling multiple file selection ...............................................5 2.6 Showing only files, only directories or both ................................5 2.7 Showing hidden files ............................................................6 2.8 Filtering files by extension ....................................................6 2.9 Filtering files on other criteria ...............................................6 1 Purpose This document is part of a series in which we look at Swing components that enable a user to enter or select data Subject(s) covered in the present document: JFileChooser dialogs JColorChooser dialogs 2 JFileChooser dialogs 2.1 Basic operation The simplest flow of operation is as follows: 1. Instantiate a JFileChooser 2. Call showOpenDialog() to make the file chooser visible as a result of a user action (typically selecting a menu option) 3. Evaluate the return value of showOpenDialog(), which indicates the user's action 4. Unless the user cancelled or closed the dialog, call getSelectedFile() or getSelectedFiles() to know the file (or files, if multiple selection was enabled) 2.2 Example In the code example below, choosing File Open from the menu opens a file chooser pointing to the user's home directory. Only one file can be selected (multiple selection disabled, which is the default). If the user selects a file and presses "Open", the file chooser closes and a message box displays the filename. import import import import java.io.*; javax.swing.*; java.awt.*; java.awt.event.*; public class WinChooser implements ActionListener { JFrame frame; Container fc; JPanel buttonPanel; JButton bExit; JMenuBar menuBar; public WinChooser() { frame = new JFrame("WinChooser"); fc = frame.getContentPane(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Dimension screenDim = frame.getToolkit().getScreenSize(); int height = screenDim.height; int width = screenDim.width; frame.setSize(width/2, height/2); frame.setLocation(20, 10); frame.setLayout(new BorderLayout()); makeButtonPanel(); makeMenu(); } void makeButtonPanel() { buttonPanel = new JPanel(); buttonPanel.setLayout(new FlowLayout()); fc.add(buttonPanel, BorderLayout.SOUTH); bExit = new JButton("Exit"); bExit.setActionCommand("=exit"); bExit.addActionListener(this); buttonPanel.add(bExit); } void makeMenu() { menuBar = new JMenuBar(); JMenu menuFile = new JMenu("File"); menuBar.add(menuFile); JMenuItem miFileOpen = new JMenuItem("Open"); menuFile.add(miFileOpen); miFileOpen.setActionCommand("=open"); miFileOpen.addActionListener(this); JMenuItem miFileExit = new JMenuItem("Exit"); miFileExit.setActionCommand("=exit"); miFileExit.addActionListener(this); menuFile.add(miFileExit); JMenu menuHelp = new JMenu("Help"); menuBar.add(menuHelp); frame.setJMenuBar(menuBar); } void selectFile() { JFileChooser chooser = new JFileChooser(); int reply = chooser.showOpenDialog(frame); if (reply == JFileChooser.APPROVE_OPTION) { File selFile = chooser.getSelectedFile(); JOptionPane.showMessageDialog(frame, selFile.getName()); } } void setVisible() { frame.setVisible(true); } public void actionPerformed(ActionEvent e) { Object eventSource = e.getSource(); String comm = e.getActionCommand(); System.out.println("command:" + comm); if (comm.equals("=open")) { selectFile(); } else if (comm.equals("=exit")) { frame.dispose(); System.exit(0); } } public static void main(String[] args) { WinChooser gui = new WinChooser(); gui.setVisible(); } } The result: Notes: The references to the selected files are returned as File objects, so the source code must contain import java.io.File or import java.io.* The call to showOpenDialog() must pass a reference to the Component where the dialog is to be displayed (here the JFrame) The int returned by showOpenDialog() must be checked against the following constants: APPROVE_OPTION CANCEL_OPTION ERROR_OPTION (if an error occurs or the dialog is dismissed) 2.3 Changing the initial directory Overloaded forms of the constructors can be used to specify the initial directory. The directory can be passed as a String or as a File object. In the code below the selectFile() method is rewritten so that the File Chooser initially shows files from the current directory instead of the user's home directory. You can obtain the current directory via the user.dir property. void selectFile() { String cwd = System.getProperty("user.dir"); System.out.println("cwd" + cwd); JFileChooser chooser = new JFileChooser(cwd); int reply = chooser.showOpenDialog(frame); if (reply == JFileChooser.APPROVE_OPTION) { File selFile = chooser.getSelectedFile(); JOptionPane.showMessageDialog(frame, selFile.getName()); } System.out.println("leaving chooseFile())"); } 2.4 Setting the dialog title Use the method setDialogTitle() 2.5 Enabling multiple file selection To enable or disable the possibility to select multiple files, call setMultiSelectionEnabled (boolean enable) If multiple selection is enabled, you must use getSelectedFiles() to retrieve the selections 2.6 Showing only files, only directories or both Use the method setFileSelectionMode() passing one of these constants: JFileChooser.FILES_AND_DIRECTORIES (default) JFileChooser.FILES_ONLY JFileChooser.DIRECTORIES_ONLY 2.7 Showing hidden files To control whether hidden files are shown, use setFileHidingEnabled(boolean hide) 2.8 Filtering files by extension Swing provides a ready-made class to filter files by extension: FileNameExtensionFilter. The constructor accepts a descriptive string and a variable number of extensions (without the leading dot). To make the file chooser use the filter, call its method addChoosableFilter(). Example: import javax.swing.filechooser.*; (...) JFileChooser chooser = new JFileChooser(...); chooser.addChoosableFileFilter(new FileNameExtensionFilter("Java files (*.java,*.class)", "java", "class")); Result: 2.9 Filtering files on other criteria To have the file choose filter files, for example to show only files with a specific extension, you must create a subclass of the abstract class FileFilter and pass this filter to the chooser. In the filter you must implement two methods: accept(), which receives a File object and returns a Boolean indicating whether this file is acceptable or not getDescription(), which returns the description of the filter Careful here: FileFilter is both an abstract class in the Swing library and a standard interface in java.io. Depending on the import statements in your class, this may lead to ambiguity and a compiler error. The safest thing is to use the full path in the "extends" clause: class FileFilterJava extends javax.swing.filechooser.FileFilter To make the chooser use the filter call setFileFilter() The code below implements the same selection logic (only Java source and class files) using a custom file filter: void selectFile() { String cwd = System.getProperty("user.dir"); System.out.println("cwd" + cwd); JFileChooser chooser = new JFileChooser(cwd); chooser.setFileFilter(new JavaFileFilter()); int reply = chooser.showOpenDialog(frame); if (reply == JFileChooser.APPROVE_OPTION) { File selFile = chooser.getSelectedFile(); JOptionPane.showMessageDialog(frame, selFile.getName()); } } (...) class JavaFileFilter extends javax.swing.filechooser.FileFilter { public String getDescription() { return "Java source/class files"; } public boolean accept(File f) { if (f.isDirectory()) { // Let directories pass through the filter, otherwise // the user can only browse in the current directory return true; } String extension = getExtension(f); if (extension == null) { return false; } System.out.println("get extension:" + extension); if (extension.equals("java") || extension.equals("class")) { return true; } return false; } 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; } } Output: Notice that the chooser automatically calls the getDescription()method of the file filter and shows the result in the "File Name" field. Selecting by extension is of course much easier using FileNameExtensionFilter, but custom file filters can be used to implement any type of filtering, e.g. on file size, age, accessibility, etc. 2.10 Choose with "Save" button Instead of an "Open" button, you can have the chooser display a "Save" button. To do this call showSaveDialog() instead of showOpenDialog()