/* File chooser demo and the values returned for file names. You can have a file filter, for example "*.java" and get a list of all the files in the directory with that extension. Mike Barnes 9/17/02 */ // FileChooserDemo from sun -- import java.io.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.filechooser.*; public class FileChooserDemo extends JFrame { static private final String newline = "\n"; public FileChooserDemo() { super("Look for *.java files"); //Create the log first, because the action listeners //need to refer to it. final JTextArea log = new JTextArea(5,20); log.setMargin(new Insets(5,5,5,5)); log.setEditable(false); JScrollPane logScrollPane = new JScrollPane(log); //Create a file chooser File currentDirectory = new File(""); final JFileChooser fc = new JFileChooser(currentDirectory); final SingleFileFilter classFilter = new SingleFileFilter("java", "Java source files"); // renzo -- add SingleFileFilter fc.addChoosableFileFilter(classFilter); //Create the open button // open.gif found in C:\j2sdk1.4.2_01\demo\jfc\Notepad\resources ImageIcon openIcon = new ImageIcon("open.gif"); JButton openButton = new JButton("Open a File...", openIcon); openButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { File [] files = null; int returnVal = fc.showOpenDialog(FileChooserDemo.this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); //this is where a real application would open the file. // renzo - add all info about file log.append("Opening: " + newline); log.append("file name: " + file.getName() + newline); log.append("path: " + file.getPath() + newline); log.append("absolute path: " + file.getAbsolutePath() + newline); try{ log.append("canonical path: " + file.getCanonicalPath() + newline); } catch (IOException ioe) {System.out.println(ioe);}; if (file.isDirectory()) log.append("A directory" + newline); else { log.append("Not a directory get parent: "); file = file.getParentFile(); log.append("Parent directory " + file.getPath() + newline); } // show files files = file.listFiles(); log.append("Directory has " + files.length + " files" + newline); for (int i = 0; i < files.length; i++) log.append("\t" + files[i] + newline); } else { log.append("Open command cancelled by user." + newline); } } }); //For layout purposes, put the buttons in a separate panel JPanel buttonPanel = new JPanel(); buttonPanel.add(openButton); //Add the buttons and the log to the frame Container contentPane = getContentPane(); contentPane.add(buttonPanel, BorderLayout.NORTH); contentPane.add(logScrollPane, BorderLayout.CENTER); } public static void main(String[] args) { JFrame frame = new FileChooserDemo(); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.pack(); frame.setVisible(true); } }