FileChooser

FileChooserDemo Example (Run Application)

package FileChooserDemo;

import java.awt.*;
import javax.swing.*;

public class FileChooserDemo extends JApplet
{
    public static void main(String[] args)
    {
        // application title and dimensions
        final String title = "FileChooser Example";
        final Dimension applicationFrameSize = new Dimension(300, 200);

        // make an application frame to hold the applet
        final JFrame applicationFrame = new JFrame(title);
        applicationFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        applicationFrame.setSize(applicationFrameSize);

        // place the applet inside the application's frame
        final JApplet applet = new FileChooserDemo();
        applicationFrame.setLayout(new BorderLayout());
        applicationFrame.getContentPane().add("Center", applet);
        applet.init();

        applicationFrame.setVisible(true);
    }

    @Override
    public void init()
    {
        this.setContentPane(new View());
    }

    public class View extends JPanel
    {
        public View()
        {
            super();

            // set up a message so that the selected file name can be
            // displayed on the applet's panel
            final JLabel message = new JLabel();
            this.add(message);

            // create a file chooser
            final JFileChooser fileChooser = new JFileChooser();

            if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
            {
                message.setText("Filename: " + fileChooser.getCurrentDirectory()
                        + "\\" + fileChooser.getSelectedFile().getName());
            }
        }
    }
}

Filters

FileChooser_Filter_Demo Example (Run Application)

package filechooser_filter_demo;

import java.awt.*;
import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;

public class FileChooser_Filter_Demo extends JApplet
{
    public static void main(String[] args)
    {
        // application title and dimensions
        final String title = "FileChooser_Filter_Demo Example";
        final Dimension applicationFrameSize = new Dimension(300, 200);

        // make an application frame to hold the applet
        final JFrame applicationFrame = new JFrame(title);
        applicationFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        applicationFrame.setSize(applicationFrameSize);

        // place the applet inside the application's frame
        final JApplet applet = new FileChooser_Filter_Demo();
        applicationFrame.setLayout(new BorderLayout());
        applicationFrame.getContentPane().add("Center", applet);
        applet.init();

        applicationFrame.setVisible(true);
    }

    @Override
    public void init()
    {
        this.setContentPane(new View());
    }

    public class View extends JPanel
    {
        public View()
        {
            super();

            // set up a message so that the selected file name can be
            // displayed on the applet's panel
            final JLabel message = new JLabel();
            this.add(message);

            // create a file chooser
            final JFileChooser fileChooser = new JFileChooser();

            // turn off the option to see all files
            fileChooser.setAcceptAllFileFilterUsed(false);

            // filter the fileChooser
            fileChooser.addChoosableFileFilter(new JpegFileFilter());
            fileChooser.addChoosableFileFilter(new GifFileFilter());

            if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
            {
                message.setText("Filename: " + fileChooser.getCurrentDirectory() + "\\" +
                                fileChooser.getSelectedFile().getName());
            }
        }

        private class JpegFileFilter extends FileFilter
        {
            @Override
            public boolean accept(File file)
            {
                if (file.isDirectory())
                {
                    return true;
                }

                final String fileName = file.getName().toLowerCase();
                return (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".jpe"));
            }

            @Override
            public String getDescription()
            {
                return ("JPEG (*.JPG, *.JPEG and *.JPE)");
            }
        }

        private class GifFileFilter extends FileFilter
        {
            @Override
            public boolean accept(File file)
            {
                if (file.isDirectory())
                {
                    return true;
                }

                final String name = file.getName().toLowerCase();
                return (name.endsWith(".gif"));
            }

            @Override
            public String getDescription()
            {
                return ("CompuServe GIF (*.GIF)");
            }
        }
    }
}

Reading and Writing Image Files

FileChooser_ImageFiles_Demo Example (Run Application)

package filechooser_imagefiles_demo;

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;

public class FileChooser_ImageFiles_Demo extends JApplet
{
    public static void main(String[] args)
    {
        // application title and dimensions
        final String title = "Application Title";
        final Dimension applicationFrameSize = new Dimension(300, 200);

        // make an application frame to hold the applet
        final JFrame applicationFrame = new JFrame(title);
        applicationFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        applicationFrame.setSize(applicationFrameSize);

        // place the applet inside the application's frame
        final JApplet applet = new FileChooser_ImageFiles_Demo();
        applicationFrame.setLayout(new BorderLayout());
        applicationFrame.getContentPane().add("Center", applet);
        applet.init();

        applicationFrame.setVisible(true);
    }

    @Override
    public void init()
    {
        this.setContentPane(new View());
    }

    public class View extends JPanel implements ActionListener
    {
        private final JButton openFile = new JButton("Open");
        private final JButton saveFile = new JButton("Save");
        private final JFileChooser fileChooser = new JFileChooser();
        private final Canvas canvas = new Canvas();    // user defined Canvas class

        public View()
        {
            super();

            // initialise the fileChooser
            this.fileChooser.setAcceptAllFileFilterUsed(false);
            this.fileChooser.addChoosableFileFilter(new JpegFileFilter());
            this.fileChooser.addChoosableFileFilter(new GifFileFilter());

            // control panel
            JPanel controlPanel = new JPanel();
            controlPanel.setLayout(new FlowLayout());
            controlPanel.add(this.openFile);
            controlPanel.add(this.saveFile);

            // initialise the applet's panel
            setLayout(new BorderLayout());
            add("South", controlPanel);
            add("Center", this.canvas);

            // add actionListeners
            this.openFile.addActionListener(this);
            this.saveFile.addActionListener(this);

            // Do not allow save until a file has been opened
            this.saveFile.setEnabled(false);
        }

        @Override
        public void actionPerformed(ActionEvent e)
        {
            Object source = e.getSource();
            if (source == this.openFile)
            {
                openFile();
            }
            else
            {
                saveFile();
            }
            this.canvas.repaint();
        }

        private void openFile()
        {
            // Open and display an image file
            if (this.fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
            {
                File imageFile = new File(this.fileChooser.getCurrentDirectory() + "\\" +
                                          this.fileChooser.getSelectedFile().getName());
                try
                {
                    this.canvas.setImage(imageFile);

                    // show and hide appropriate buttons
                    this.openFile.setEnabled(false);
                    this.saveFile.setEnabled(true);
                }
                catch (Exception e)
                {
                }
            }
        }

        private void saveFile()
        {
            // Save the same image file
            if (this.fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
            {

                File imageFile = new File(this.fileChooser.getCurrentDirectory() + "\\" +
                                          this.fileChooser.getSelectedFile().getName());
                try
                {
                    String fileType = this.fileChooser.getSelectedFile().getName();
                    if (fileType.contains(".gif"))
                    {
                        fileType = "gif";
                    }
                    else
                    {
                        fileType = "jpg";
                    }

                    ImageIO.write(canvas.getImage(), fileType, imageFile);

                    // show and hide appropriate buttons
                    this.openFile.setEnabled(true);
                    this.saveFile.setEnabled(false);
                    this.canvas.setImage(null);
                }
                catch (Exception e)
                {
                }
            }
        }

        private class JpegFileFilter extends FileFilter
        {
            @Override
            public boolean accept(File file)
            {
                if (file.isDirectory())
                {
                    return true;
                }

                String fileName = file.getName().toLowerCase();
                return (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".jpe"));
            }

            @Override
            public String getDescription()
            {
                return ("JPEG (*.JPG, *.JPEG and *.JPE)");
            }
        }

        private class GifFileFilter extends FileFilter
        {
            @Override
            public boolean accept(File file)
            {
                if (file.isDirectory())
                {
                    return true;
                }

                String name = file.getName().toLowerCase();
                return (name.endsWith(".gif"));
            }

            @Override
            public String getDescription()
            {
                return ("CompuServe GIF (*.GIF)");
            }
        }
    }

    public class Canvas extends JPanel
    {
        private BufferedImage image = null;

        public Canvas()
        {
            super();
        }

        public void setImage(File imageFile)
        {
            if (imageFile != null)
            {
                try
                {
                    image = ImageIO.read(imageFile);
                }
                catch (Exception e)
                {
                }
            }
            else // imageFile == null
            {
                // reset the image to empty
                image = null;
            }
        }

        public BufferedImage getImage()
        {
            return image;
        }

        @Override
        public void paintComponent(Graphics g)
        {
            //super.paintComponent(g);
            if (this.image != null)
            {
                final Graphics2D g2d = this.image.createGraphics();

                // perform a simple manipulatation of the inputted image
                g2d.setColor(Color.red);
                g2d.fillOval(this.image.getWidth() / 4, this.image.getHeight() / 4,
                             this.image.getWidth() / 2, this.image.getHeight() / 2);

                // paint the modified image
                g.drawImage(this.image, 0, 0, this.getWidth(), this.getHeight(), this);
            }
            else // no image displayed yet
            {
                g.setColor(Color.white);
                g.fillRect(0, 0, this.getWidth(), this.getHeight());
                g.setColor(Color.black);
                g.drawString("Select an image to display", 10, this.getHeight() / 2);
            }
        }
    }
}
 
<div align="center"><a href="../versionC/index.html" title="DKIT Lecture notes homepage for Derek O&#39; Reilly, Dundalk Institute of Technology (DKIT), Dundalk, County Louth, Ireland. Copyright Derek O&#39; Reilly, DKIT." target="_parent" style='font-size:0;color:white;background-color:white'>&nbsp;</a></div>