import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.filechooser.FileNameExtensionFilter;
public class FileChooserFrame extends JFrame {
private JPanel panel = null;
private JTextArea area = null;
public FileChooserFrame(){
Container con = this.getContentPane();
con.add(createPanel());
this.setSize(600,400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setDefaultLookAndFeelDecorated(true);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public JPanel createPanel(){
panel = new JPanel();
area = new JTextArea();
panel.add(area);
panel.add(createButton("save"));
panel.add(createButton("open"));
return panel;
}
public JButton createButton( String name ){
JButton button = new JButton(name);
button.addActionListener(new FileActionListener(this) );
return button;
}
public static void main(String[] args) {
new FileChooserFrame();
}
class FileActionListener implements ActionListener {
FileChooserFrame frame ;
public FileActionListener( FileChooserFrame frame ){
this.frame = frame;
}
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if( command.equals("save") ){
JFileChooser fileChooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("gif & jpg images ","jpg","gif");
fileChooser.setFileFilter(filter);
int d = fileChooser.showSaveDialog(frame);
if( d==fileChooser.APPROVE_OPTION ){
File file = fileChooser.getSelectedFile();
frame.getArea().append(file.getName());
}
}
}
}
public JTextArea getArea() {
return area;
}
public void setArea(JTextArea area) {
this.area = area;
}
}