Like us on Facebook and stand a chance to win pen drives!

Swing File Chooser Demo




package main;

import java.awt.BorderLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class SwingFileChooser extends JPanel implements ActionListener{
private static final String newLine = "\n";
private JButton openButton,saveButton;
private JTextArea log;
private JFileChooser fc;

public SwingFileChooser(){
super(new BorderLayout());
initComponents();

}

private void initComponents(){
log = new JTextArea();
log.setMargin(new Insets(5, 5, 5, 5));
log.setEditable(false);
JScrollPane jsp = new JScrollPane(log);
fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
openButton = new JButton("Open File");
openButton.addActionListener(this);
saveButton = new JButton("Save File");
saveButton.addActionListener(this);
JPanel buttonPanel = new JPanel();
buttonPanel.add(openButton);
buttonPanel.add(saveButton);
add(buttonPanel,BorderLayout.NORTH);
add(jsp,BorderLayout.CENTER);
}

@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == openButton){
int returnVal = fc.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION){
File file = fc.getSelectedFile();
log.append("Opening " + file.getName() + newLine);
}else{
log.append("cancelled file opening" + newLine);
}
log.setCaretPosition(log.getDocument().getLength());

}else if(e.getSource() == saveButton){
int returnVal = fc.showSaveDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION){
File file = fc.getSelectedFile();
log.append("Saving " + file.getName() + newLine);
}else{
log.append("cancelled file saving" + newLine);
}
log.setCaretPosition(log.getDocument().getLength());
}
}

private static void createGUI(){
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("SwingFileChooser");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JComponent newContentPane = new SwingFileChooser();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {

@Override
public void run() {
createGUI();
}
});

}
}


1 comment:

  1. whoah this blog is fantastic i love studying your articles.
    Keep up the great work! You already know,
    a lot of individuals are searching around for this information, you can aid
    them greatly.

    ReplyDelete

Copyright © 2012 The Code Junction.