Image Viewer using JFileChooser

FileChosser

The JFileChooser class in the javax.swing package provides an easy-to-use mechanism for creating file dialogs for opening and saving files. The JFileChooser class is slightly out of kilter with the new input/output capability in that it uses java.io.File objects to encapsulate file paths. If you can change the current directory at any time by passing a File object specifying the directory you want to make current to the setCurrentDirectory() method.

You need a file open dialog, you can call the showOpenDialog() member of a JFileChooser object. The method returns can be constants that are defined in the JFileChooser class:

APPROVE_OPTION if the approve button was clicked.

if you have enabled multiple selections in the dialog, calling the getSelectedFiles() method for the dialog object returns an array of File objects corresponding to the selected files.

Program

import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.FlowLayout;
import java.io.File;

class JMenuBarTest extends JFrame implements ActionListener{
  
    private JMenuItem   open;
    private JFileChooser fc;
    private JLabel jl;
            
    JMenuBarTest()
    {
        setTitle("Image Viewer");
        setLayout(new FlowLayout());
        setJMenuBarAndMenuBarItems();
        setJFileChooser();
        setJLabel();
        setAction();
        setSize(700,500);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
  
    void setJMenuBarAndMenuBarItems()
    {
        JMenuBar menuBar = new JMenuBar();
        JMenu menu1    = new JMenu("File");
        open     = new JMenuItem("Open");
        menu1.add(open);
        menuBar.add(menu1);
        setJMenuBar(menuBar);
    }
    
    void setJLabel()
    {
        jl = new JLabel();
        add(jl);
    }
    
    void setJFileChooser()
    {
        fc = new JFileChooser();
        fc.setCurrentDirectory(new File("."));
    }
  
    void setAction()
    {
        open.addActionListener(this);
    }
  
    public void actionPerformed(ActionEvent eve)
    {
        int getfile;
        if(eve.getSource() == open)
        {
            getfile = fc.showOpenDialog(rootPane);
            if(getfile==JFileChooser.APPROVE_OPTION)
            {
                jl.setIcon(new ImageIcon(fc.getSelectedFile().getPath()));
            }
        }
    }
}

public class Javaapp {
  
    public static void main(String[] args) {
      
        JMenuBarTest imageviewer = new JMenuBarTest();
    }
}


Program Output

Leave a Comment