Listing 15.1 JFileChooser Application with Open and Save File Choosers (TJFileChooser.java) // Demonstrates the Swing file choosers import javax.swing.*; import javax.swing.border.*; import java.awt.*; import java.awt.event.*; import java.io.*; // 1. The class TJFileChooser frame. public class TJFileChooser extends JFrame { JMenuItem openMI, saveMI, saveAsMI, exitMI; JFileChooser fileChooser; Container container; JLabel label; File file, selectedFile; public TJFileChooser() { // 2. To close the frame. this.addWindowListener(new FrameClosing()); // 3. Get a handle on the frame's content pane. container = this.getContentPane(); // 4. Create a label and add it to the container. label = new JLabel(); container.add(label); // 5. Create and add a menu bar. JMenuBar menuBar = new JMenuBar(); menuBar.setBorder(BorderFactory.createEtchedBorder()); container.add(menuBar, BorderLayout.NORTH); // 6. Create and add the file menu and its menu items. JMenu fileMenu = new JMenu("File"); menuBar.add(fileMenu); JMenuItem newMI = new JMenuItem("New"); newMI.setEnabled(false); fileMenu.add(newMI); openMI = new JMenuItem("Open"); openMI.addActionListener(new MIActionListener()); fileMenu.add(openMI); fileMenu.addSeparator(); saveMI = new JMenuItem("Save"); saveMI.setEnabled(false); fileMenu.add(saveMI); saveAsMI = new JMenuItem("Save As"); saveAsMI.addActionListener(new MIActionListener()); fileMenu.add(saveAsMI); fileMenu.addSeparator(); fileMenu.addSeparator(); // 7. "Exit" menu item with an action listener. exitMI = new JMenuItem("Exit"); exitMI.addActionListener(new MIActionListener()); fileMenu.add(exitMI); // 8. Create and add the Edit menu. JMenu editMenu = new JMenu("Edit"); menuBar.add(editMenu); } // 9. Menu action listener. class MIActionListener implements ActionListener { public void actionPerformed(ActionEvent ae) { JMenuItem menuItem = (JMenuItem) ae.getSource(); // 10. If the Open menu item is selected. if (menuItem == openMI) { if (file == null) { // Create a file chooser pointing to the // home directory fileChooser = new JFileChooser(); } else { // Create a file chooser pointing to the // specified file path fileChooser = new JFileChooser(file); } // Show the dialog box (returns the option selected). int selected = fileChooser.showOpenDialog(container); // 11. If the Open button over the file chooser is pressed. if (selected == JFileChooser.APPROVE_OPTION) { // Get the selected file file = fileChooser.getSelectedFile(); // Display the file name in the frame. label.setText("You have selected to open:"+ file.getName()); label.setHorizontalAlignment(JLabel.CENTER); return; } // 12. If the Cancel button is pressed. else if (selected == fileChooser.CANCEL_OPTION) { label.setText("You have not selected any file to open!"); label.setHorizontalAlignment(JLabel.CENTER); return; } } // 13. If the Save menu item is selected. else if (menuItem == saveAsMI) { // Here comes your file-saving code... fileChooser = new JFileChooser(); int selected = fileChooser.showSaveDialog(container); selectedFile = new File("UNTITLED"); fileChooser.setSelectedFile(selectedFile); if (selected == JFileChooser.APPROVE_OPTION) { // Get the selected file selectedFile = fileChooser.getSelectedFile(); // Display the selected file name in the frame. label.setText("You have selected to save:"+ file.getName()); label.setHorizontalAlignment(JLabel.CENTER); return; } else if (selected == fileChooser.CANCEL_OPTION) { label.setText("You have not selected any file to open!"); label.setHorizontalAlignment(JLabel.CENTER); return; } } else if (menuItem == exitMI) { System.exit(0); } } } // 14. Listener to close the frame. class FrameClosing extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } } // 15. The main method. public static void main(String[] args) { TJFileChooser frame = new TJFileChooser(); frame.setTitle("TJFileChooser Example"); frame.setSize(450, 300); frame.setVisible(true); } } Listing 15.2 JFileFilter with File Filters and Custom File View (TJFileFilter.java) Demonstrates the file filters and custom file view. import javax.swing.*; import javax.swing.border.*; import java.awt.*; import java.awt.event.*; import java.io.*; public class TFileFilter extends JFrame { JMenuItem openMI, exitMI; JFileChooser fileChooser; Container container; JLabel label; File file, selectedFile; public TFileFilter() { // 1. To close the frame. this.addWindowListener(new FrameClosing()); // 2. Get a handle on the frame's content pane. container = this.getContentPane(); // 3. create a label and add it to the container. label = new JLabel(); container.add(label); // 4. Create and add a menu bar. JMenuBar menuBar = new JMenuBar(); menuBar.setBorder(BorderFactory.createEtchedBorder()); container.add(menuBar, BorderLayout.NORTH); // 5. Create and add the file menu and its menu items. JMenu fileMenu = new JMenu("File"); menuBar.add(fileMenu); openMI = new JMenuItem("Open"); openMI.addActionListener(new MIActionListener()); fileMenu.add(openMI); fileMenu.addSeparator(); // 6. "Exit" menu item with an action listener. exitMI = new JMenuItem("Exit"); exitMI.addActionListener(new MIActionListener()); fileMenu.add(exitMI); } // 7. Menu action listener. class MIActionListener implements ActionListener { public void actionPerformed(ActionEvent ae) { JMenuItem menuItem = (JMenuItem) ae.getSource(); // 8. if the "Open" menu item is selected. if (menuItem == openMI) { if (file == null) { // Create a file chooser pionting to the // home directory. fileChooser = new JFileChooser(); } else { // Create a file chooser pointing to the // specified file path. fileChooser = new JFileChooser(file); } // 9. Add a file filter (object of MyFileFilter). fileChooser.addChoosableFileFilter(new MyFileFilter()); // The following statement will assign the new filter // discarding the other filters. //fileChooser.setFileFilter(new MyFileFilter()); // 10. Set a custom view for the files (using the object of MyFileView). fileChooser.setFileView(new MyFileView()); // 11. Show the dialog box (returns the option selected). int selected = fileChooser.showOpenDialog(container); // 12. if the Open button over the file chooser is pressed. if (selected == JFileChooser.APPROVE_OPTION) { // Get the selected file file = fileChooser.getSelectedFile(); // Display the file name in the frame. label.setText("You have selected to open:"+ file.getName()); label.setHorizontalAlignment(JLabel.CENTER); return; } // 13. if the Cancel button is pressed. else if (selected == fileChooser.CANCEL_OPTION) { label.setText("You have not selected any file to open!"); label.setHorizontalAlignment(JLabel.CENTER); return; } } // 14. If the Exit button is pressed. else if (menuItem == exitMI) { System.exit(0); } } } // 15. Listener to close the frame. class FrameClosing extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } } // 16. The main method. public static void main(String[] args) { TFileFilter frame = new TFileFilter(); frame.setTitle("TFileFilter Example"); frame.setSize(450, 300); frame.setVisible(true); } } // 17. Define a file filter class. class MyFileFilter extends javax.swing.filechooser.FileFilter { public boolean accept(File file) { if (file.isDirectory()) { // Accept if the file system member is a directory return true; } // Retrieve the file name. String fileName = file.getName(); // Note the index of '.' in a file name int periodIndex = fileName.lastIndexOf('.'); // State of acceptence. boolean accepted = false; if (periodIndex>0 && periodIndex<fileName.length()-1) { String extension = fileName.substring(periodIndex+1).toLowerCase(); if (extension.equals("java")) // Check if the extension is ".java" accepted = true; else if(extension.equals("html")) // Check if the extension is .html. accepted = true; } return accepted; } // Retrieve the description of the filter. public String getDescription() { return "Java and HTML Files (*.java, *.html))"; } } // 18. Custom file view class. class MyFileView extends javax.swing.filechooser.FileView { // Define the required icon objects. ImageIcon javaIcon = new ImageIcon("javaIcon.gif"); ImageIcon htmlIcon = new ImageIcon("htmlIcon.gif"); // Retrieve the file name. public String getName(File f) { return null; // L&F FileView will find this out // of use return f.getName(); } // Retrieve the description of the file. public String getDescription(File f) { return null; // L&F FileView will find this out } // Returns the file type as Java. public String getTypeDescription(File f) { String extension = getExtension(f); String type = null; if(extension != null) { if(extension.equals("java")) { type = "Java File"; } if(extension.equals("gif")){ type = "Html File"; } } return type; } // Retrieve the relevant icon for the file view. public Icon getIcon(File f) { String extension = getExtension(f); Icon icon = null; if (extension != null) { if(extension.equals("java")) { icon = javaIcon; } if(extension.equals("html")) { icon = htmlIcon; } } return icon; } // Whether a direction is traversable. public Boolean isTraversable(File f) { return null; // L&F FileView will find this out } // Retrieve the extension of a file. private String getExtension(File f) { String fileName = f.getName(); int periodIndex = fileName.lastIndexOf('.'); String extension = null; if(periodIndex > 0 && periodIndex < fileName.length() - 1) { extension = fileName.substring(periodIndex+1).toLowerCase(); } return extension; } } Listing 15.3 JColorChooser in a Simple Drawing Applet (TJColorChooser.java) /* * <Applet code=TJColorChooser width=400 height=400> * </Applet> */ import javax.swing.*; import java.awt.*; import java.awt.event.*; public class TJColorChooser extends JApplet { Container container = null; DrawingPanel panel = null; JColorChooser colorChooser = null; JDialog dialog = null; int oldX, oldY, newX, newY; Color color = null; public void init() { // 1. Get a handle on the applet's content pane. container = this.getContentPane(); // 2. Create a drawing panel and add it at the center // of the content pane of the applet. panel = new DrawingPanel(); container.add(panel); // 3. Add a button at the bottom portion // of the applet to display the color chooser pane. JButton showButton = new JButton("Show Color Chooser"); showButton.addActionListener(new ButtonListener()); Box hBox = Box.createHorizontalBox(); hBox.add(Box.createHorizontalGlue()); hBox.add(showButton); hBox.add(Box.createHorizontalGlue()); container.add(hBox, BorderLayout.SOUTH); // 4. Create a color chooser object and a dialog box // that displays the color chooser. colorChooser = new JColorChooser(); dialog = JColorChooser.createDialog( container, "Color Chooser", false, colorChooser, new ButtonListener(), new ButtonListener()); } // 5. This is where you perform your drawing with // the selected color. class DrawingPanel extends Panel { public DrawingPanel () { setBackground(Color.white); MyMouseListener mouseListener = new MyMouseListener(); addMouseListener(mouseListener); addMouseMotionListener(mouseListener); } public void update(Graphics g) { g.setColor(color); paint(g); } public void paint(Graphics g) { g.drawLine(oldX, oldY, newX, newY); } } // 6. Listener class that responds to all button actions. class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { JButton button = (JButton) e.getSource(); if (button.getText().equals("Show Color Chooser")) { dialog.show(); } if (button.getText().equals("OK")) { //dialog.show(); color = colorChooser.getColor(); } else if(button.getText().equals("Cancel")) { dialog.dispose(); } // Note: Don't have to handle the actions of the // 'Reset' button; this button has been implemented // to reset the color to the previously used color. } } // 7. Mouse listener class to draw on the canvas. class MyMouseListener extends MouseAdapter implements MouseMotionListener { public void mousePressed(MouseEvent e) { oldX = e.getX(); oldY = e.getY(); newX = e.getX(); newY = e.getY(); panel.repaint(); } public void mouseDragged(MouseEvent e) { oldX = newX; oldY = newY; newX = e.getX(); newY = e.getY(); panel.repaint(); } public void mouseMoved(MouseEvent e) {} } }