Sat May 23, 2009 4:21 pm
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.*;
import javax.swing.text.*;
import java.io.*;
/**
* Class <code>FileChooser</code> is used to demo opening and closing file.
*
* @author Mely
* @version 1.73, 03/30/06
* @see javax.swing.filechooser.JFileChooser;
* @since JDK1.0
*/
public class FileChooser extends JFrame {
private JTextArea log;
private static final JFileChooser fc = new JFileChooser();
private static final String txt = ".txt";
static {
//Add a custom file filter and disable the default
//(Accept All) file filter.
//fc.addChoosableFileFilter(new TxtFilter());
fc.setAcceptAllFileFilterUsed(false);
}
private String newline = System.getProperty("line.separator");
public FileChooser() {
super("FileChooserDemo");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(400, 200);
JButton openButton = new JButton("Open", new ImageIcon("images/open.gif")); //Create the open button and add image
openButton.addActionListener(new OpenListener()); //Adds action listener to the open button
JButton saveButton = new JButton("Save", new ImageIcon("images/save.gif")); //Create the save button and add image
saveButton.addActionListener(new SaveListener()); //Adds action listener to the save button
Dimension btnSize = new Dimension(100, 30);
openButton.setPreferredSize(btnSize);
saveButton.setPreferredSize(btnSize);
JPanel buttonPanel = new JPanel(); //Create a panel
buttonPanel.add(openButton); //Add the open button to the panel
buttonPanel.add(saveButton); //Add the save button to the panel
log = new JTextArea(5,20); //Create the text area
log.setMargin(new Insets(5,5,5,5)); //Set the margins
JScrollPane logScrollPane = new JScrollPane(log);
Container contentPane = getContentPane();
contentPane.add(buttonPanel, BorderLayout.PAGE_START); //Add the buttons to the panel
contentPane.add(logScrollPane, BorderLayout.CENTER); //Add the text area to the panel
} //end of constructor
/**
* Find the hosting frame, for the file-chooser dialog.
*
* @return a frame of this parent.
*/
protected Frame getFrame() {
for (Container p = getParent(); p != null; p = p.getParent())
if (p instanceof Frame)
return (Frame) p;
return null;
}
private class OpenListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
int returnVal = fc.showOpenDialog(FileChooser.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
log.append("Opening: " + file.getName() + "." + newline); //Display "Opening" and the retrieved file name in the text area
} else
log.append("Open command cancelled by user." + newline); //Display this command in the text area
}
} //end of class OpenListener
private class SaveListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
int returnVal = fc.showSaveDialog(FileChooser.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (file.exists()) {
//default icon, custom title
int n = JOptionPane.showConfirmDialog(
getFrame(),
"File already exists. Would you like to override it?",
"Override File?",
JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.NO_OPTION) {
//log.append("Save command cancelled by user. User do not wish to override it." + newline); //Display this command in the text area
JOptionPane.showMessageDialog(getFrame(),"Save command cancelled by user. User do not wish to override it.");
return;
}
} //end of if (file.exists())
boolean isAcceptedExtension = fc.accept(file);
if (!isAcceptedExtension) {
//Custom button text
Object[] options = {"Yes, please",
"No, thanks",
"Don't do anything"};
int n = JOptionPane.showOptionDialog(getFrame(),
"The file name does not have '.txt' extension.\n\n"
+ "Would you like the program to append '.txt' to the filename on behalf of you?\n\n"
+ String.format("<html><body>Changing filename from <span style='font-family: monospace'><font color=#ff0000>'%s'</font> to <font color=#ff0000>'%s.txt'</font></span></body></html>\n", file.getPath(), file.getPath()),
"A Confirmation Question",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[2]);
if (n == JOptionPane.YES_OPTION) {
file = makeTxt(file);
isAcceptedExtension = true;
}
} //end of if (!isAcceptedExtension)
if (isAcceptedExtension) {
Thread saver = new FileSaver(file, log.getDocument());
saver.start();
//log.append("Saving: " + file.getName() + "." + newline); //Display "Saving" and the retrieved file name in the text area
JOptionPane.showMessageDialog(getFrame(),"Saving : " + file.getName() + ".");
} else
//log.append("Saving Failed: " + file.getName() + " does not END with (.txt)." + newline); //Display "Saving" and the retrieved file name in the text area
JOptionPane.showMessageDialog(getFrame(),"Saving Failed....");
} else
log.append("Save command cancelled by user." + newline); //Display this command in the text area
}
} // end of class SaveListener
public static void main(String s[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new FileChooser().setVisible(true);//Set frame to visible
}
});
}
/**
* Changed the extension to .txt if it has not done.
*
* @param f file to be changed.
* @return File that has been changed.
*/
private File makeTxt(File f) {
return f.getName().endsWith(txt) ? f : new File(f.getPath().concat(txt));
}
/**
* Thread to save a document to file
*/
private class FileSaver extends Thread {
private Document doc;
private File f;
FileSaver(File f, Document doc) {
setPriority(4);
this.f = f;
this.doc = doc;
}
public void run() {
JComponent status = new JPanel();
JFrame frame = new JFrame("Saving...");
try {
// initialize the statusbar
status.removeAll();
JProgressBar progress = new JProgressBar();
progress.setMinimum(0);
progress.setMaximum((int) doc.getLength());
status.add(progress);
status.revalidate();
Container c = frame.getContentPane();
c.setLayout(new BoxLayout(c, BoxLayout.PAGE_AXIS));
c.add(status);
c.add(new JLabel(String.format("Saving file '%s' in '%s'", f.getName(), f.getPath())));
c.add(new JLabel("Please wait..."));
frame.pack();
frame.setVisible(true);
halt(2000);
// start writing
Writer out = new FileWriter(f);
Segment text = new Segment();
text.setPartialReturn(true);
int charsLeft = doc.getLength();
int offset = 0;
while (charsLeft > 0) {
doc.getText(offset, Math.min(4096, charsLeft), text);
out.write(text.array, text.offset, text.count);
charsLeft -= text.count;
offset += text.count;
progress.setValue(offset);
halt(10);
}
out.flush();
out.close();
} catch (IOException e) {
final String msg = e.getMessage();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(getFrame(),
"Could not save file: " + msg,
"Error saving file",
JOptionPane.ERROR_MESSAGE);
}
});
} catch (BadLocationException e) {
System.err.println(e.getMessage());
}
// we are done... get rid of progressbar
status.removeAll();
status.revalidate();
halt(2000);
frame.setVisible(false);
}
} // end of class FileSaver
/**
* Waiting for the human's eye to grasp the information.
*/
private static final void halt(int ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException exception) {
System.err.println("Thread had been interrupted..");
}
}
} // end of FileChooser
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com
Powered by phpBB © phpBB Group.