package gui1;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;

public class FileChooserFrame extends JFrame {
    private JButton open, save;
    private JTextField tp;
    private JFileChooser chooser;
    private FileFinder fileFinder;
    
    public FileChooserFrame() {
        setTitle("File Chooser Demo");
        setSize(500, 100);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        chooser = new JFileChooser();
        fileFinder = new FileFinder();
        getContentPane().setLayout(new FlowLayout());
        
        open = new JButton("Open");
        open.addActionListener(fileFinder);
        getContentPane().add(open);
        
        save = new JButton("Save");
        save.addActionListener(fileFinder);
        getContentPane().add(save);
        
        tp = new JTextField(50);
        getContentPane().add(tp);
        
        tp.setText("Program started");
    }
    
    public class FileFinder implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            int option = (e.getSource() == open) 
                ? chooser.showOpenDialog(FileChooserFrame.this) 
                : chooser.showSaveDialog(FileChooserFrame.this);
            if (option == JFileChooser.APPROVE_OPTION) {
                File f = chooser.getSelectedFile();
                tp.setText("Selection of file " + f.getAbsolutePath() + " approved");
            } else if (option == JFileChooser.CANCEL_OPTION) {
                tp.setText("Selection cancelled");
            } else {
                tp.setText("Mysterious return value");
            }
        }
    }
    
    public static void main(String[] args) {
        FileChooserFrame fcf = new FileChooserFrame();
        fcf.setVisible(true);
    }
}
