Screenshot of gui, choose where to save question - java

I have a program that takes a screenshot of my gui. It automatically saves the .gif file to the eclipse project directory. What I would like is to have it asking a user where to save the image. Basically so the user can browse the file directory and choose the directory.
Here's the code I have:
public void actionPerformed(ActionEvent event) {
try{
String fileName = JOptionPane.showInputDialog(null, "Save file",
null, 1);
if (!fileName.toLowerCase().endsWith(".gif")){
JOptionPane.showMessageDialog(null, "Error: file name must end with \".gif\".",
null, 1);
}
else{
BufferedImage image = new BufferedImage(panel2.getSize().width,
panel2.getSize().height, BufferedImage.TYPE_INT_RGB);
panel2.paint(image.createGraphics());
ImageIO.write(image, "gif", new File(fileName));
JOptionPane.showMessageDialog(null, "Screen captured successfully.",
null, 1);
}
}
catch(Exception e){}

I would use a file chooser dialog instead of a JOptionPane. Here is a link for the tutorial.
Example:
First of all you have to declare JFileChooser object in your class and initialize it.
public Class FileChooserExample{
JFileChooser fc;
FileChooserExample(...){
fc = new JFileChooser();// as a parameter you can put path to initial directory to open
...
}
Now create another method:
private String getWhereToSave(){
int retVal = fc.showSaveDialog(..);
if(retVal == JFileChooser.APPROVE_OPTION){
File file = fc.getSelectedFile();
return file.getAbsolutePath();
}
return null;
}
This method returns to you the absolute path which user selected. retVal indicates which button was pressed (Save or Cancel). And if it was pressed Save then you handle the selected file.
Then you have this method you can incorporate this with your code. Instead of this line:
String fileName = JOptionPane.showInputDialog(null, "Save file", null, 1);
Write:
String fileName = getWhereToSave();

Related

JFileChooser.SetCurrentDirectory not working

I have a JFileChooser and I want to set the directory it opens using some information stored in a .txt file (I'm using a .txt file to persist the desired location between sessions). I can get the file, read the data and set it to a string, but when I try to use that string to set the directory I want to open it doesn't work. My code is roughly something like this:
//buffer contains a byte[] for "/Users/user/Documents/Work/folderToOpen"
desiredPath = new String(buffer);
jFileChooser1.setCurrentDirectory(new java.io.File(desiredPath));
After stepping through this, however, the current directory is set to /Users/user.
If anyone has any ideas about what I'm doing wrong or a better way to accomplish this I'd love to hear it.
Thank you
private static String LAST_FOLDER_USED = null;
//Get the desired file path for user preferences
String pluginRoot = System.getProperty("user.dir") + File.separator.toString();
//Create a file using the desired file Path
File userPreferences = new File(pluginRoot + File.separator + "UserPreferences.txt");
//Get a file called UserPreferences.txt from target/classes to create an input stream
String fileName = "UserPreferences.txt";
InputStream readInFile = getClass().getResourceAsStream(fileName);{
//Convert input stream to read from the desired file in the plug-in root ("filePath" Created Above)
try{
readInFile = new FileInputStream(userPreferences);
}
catch (IOException e){
e.printStackTrace();
}}
//Read the readInFile into a byte[]
String desiredPathToOpenImage;
byte[] buffer = new byte[1000];
int i = 0;{
try {
while((i = readInFile.read(buffer)) !=-1){
System.out.println(new String(buffer));
i++;
}}
catch (IOException e) {
e.printStackTrace();
};
//Convert byte[] to string (This should be the path to the desired folder when selecting an image)
desiredPathToOpenImage = new String(buffer);
}
//Create a New File using the desired path
File desiredPath = new File(desiredPathToOpenImage + File.separator + "prefs.txt");
public SelectImage(Viewer parent, boolean modal) {
super(parent, modal);
initComponents();
int returnVal = jFileChooser1.showOpenDialog(parent);
// Sets up arrays for storing file information to be passed back to the viewer class.
String[] filePath = new String[jFileChooser1.getSelectedFiles().length];
String[] fileName = new String[jFileChooser1.getSelectedFiles().length];
String[] fileDir = new String[jFileChooser1.getSelectedFiles().length];
if (returnVal == JFileChooser.APPROVE_OPTION) {
// Cycles through the selected files and stores each piece accordingly
for (int i = 0; i < jFileChooser1.getSelectedFiles().length; i++) {
File file = jFileChooser1.getSelectedFiles()[i];
filePath[i] = file.getPath();
fileName[i] = file.getName();
fileDir[i] = file.getParent();
}
}
parent.setFilePath(filePath, fileName, fileDir);
}
private void initComponents() {
jFileChooser1 = new javax.swing.JFileChooser();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jFileChooser1.setMultiSelectionEnabled(true);
//Checks folder_Path to see if a value is present. If value is present sets jFileChooser Directory to that value
if(desiredPathToOpenImage.contains(File.separator)){
//Create a File using the desired path for selecting images
//****Currently doesn't set the Directory correctly****//
jFileChooser1.setCurrentDirectory(desiredPath);
}
//If no value is present in LAST_FOLDER_USED sets jFileChooser Directory to desktop
else{
jFileChooser1.setCurrentDirectory(new java.io.File("/Users/benwoodruff/Desktop"));
}
jFileChooser1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jFileChooser1ActionPerformed(evt);
//After file is selected sets value of LAST_FOLDER_USED to the absolute path of that file
LAST_FOLDER_USED = jFileChooser1.getCurrentDirectory().toString() + File.separator + "UserPreferences.txt";
try {
FileWriter fileWriter = new FileWriter(userPreferences);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(jFileChooser1.getCurrentDirectory().toString());
OutputStream outPut = new FileOutputStream(pluginRoot + File.separator + "UserPreferences.txt");
outPut.write(LAST_FOLDER_USED.getBytes());
outPut.close();
bufferedWriter.close();
} catch (IOException e) {
System.out.println("Error Writing to File" + desiredPathToOpenImage);
e.printStackTrace();
}
}
});
I think the directory passed as argument does not exist or is not accessible to the user you are logged in with judging from the javadoc of setCurrentDirectory():
If the file passed in as currentDirectory is not a directory, the parent of the file will be used as the currentDirectory. If the parent is not traversable, then it will walk up the parent tree until it finds a traversable directory, or hits the root of the file system.
Make sure all folders in the given path exist and are accessible to the logged user (on linux the 'executable' bit controls the accessibility of a directory). So if you see something like
-d x Documents
after executing
ls -l *
in a shell then the Documents directory is accessible.
Found a better way to accomplish my goal using Preferences instead of trying to create and access files to store the location.
Preferences prefs = Preferences.userNodeForPackage(this.getClass());
static String LAST_FOLDER_USED = "LAST_FOLDER_USED";
String folder_Location;
and then inside initComponents()
if(LAST_FOLDER_USED != null){
jFileChooser1.setCurrentDirectory(new File(prefs.get(LAST_FOLDER_USED, LAST_FOLDER_USED)));
}
else{
jFileChooser1.setCurrentDirectory(new java.io.File("/Users/benwoodruff/Desktop"));
}
jFileChooser1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jFileChooser1ActionPerformed(evt);
folder_Location = jFileChooser1.getCurrentDirectory().toString();
prefs.put(LAST_FOLDER_USED, folder_Location);
//System.out.println(prefs.get(LAST_FOLDER_USED, folder_Location));
}
});

JFileChooser showSaveDialog show an error message when file name is blank or empty

The code works to check for non-empty/whitespace AbsolutePath, but not when the AbsolutePath is simply blank. Clicking save does nothing and the JFileChooser stays in showSaveDialog().
I want to show a JOptionPane error message when the user attempts to save the file with an empty-whitespace file name.
try {
JFileChooser chooser = new JFileChooser("./");
FileNameExtensionFilter filter = new FileNameExtensionFilter("files (txt)", "txt");
chooser.setFileFilter(filter);
chooser.setMultiSelectionEnabled(false);
chooser.setSelectedFile(new File(fileName));
int value = chooser.showSaveDialog(this);
if (value == JFileChooser.APPROVE_OPTION) {
String filename = chooser.getSelectedFile().getAbsolutePath();
if (chooser.getSelectedFile().getName().trim().equals("")
|| !chooser.getSelectedFile().getName().endsWith(".txt")
|| chooser.getSelectedFile().getName().replaceAll(".txt", "").trim().equals("")) {
throw new IllegalArgumentException();
}
saveFile(filename);
}
} catch (IllegalArgumentException e) {
JOptionPane.showMessageDialog(this, "Fail! File was not saved", "Error", JOptionPane.ERROR_MESSAGE);
}
Clicking save does nothing and the JFileChooser stays in showSaveDialog(). as #camickr said above: this is the built in functionality of the JFileChooser and has nothing to do with your code. The file chooser doesn't close unless you enter a filename (and click Save) or use the Cancel button..

How to Get selected folder name in java using JFileChooser?

I want to select the folder that is selected.
JFileChooser targetDir = new JFileChooser();
targetDir.setDialogTitle("Choose Target Directory.");
targetDir.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if(targetDir.showOpenDialog(null)==JFileChooser.APPROVE_OPTION)
{
System.out.println(targetDir.getCurrentDirectory());
main_mw = new MainWindow("XYZ Copier");
main_mw.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
} else {
System.exit(0);
}
} else {
}
It gives the output "/home/rahul/Downloads/mc"
but I need "/home/rahul/Downloads/mc/lib". It gives same result if i go inside lib.
Screenshots:
JFileChooser#getSelectedFile will return the selected file/directory
getCurrentDirctory returns the directory which is currently been shown in the chooser

Java: replacing a new file

I draw an image on a panel by using BufferedImage, and now I want to export that image.
But how can I detect if the new file is created or replace the old one? right now my output is:
old filename: image.jpeg
new filename: image.jpeg.jpeg
How can I do it?? I put a detect code after the file is created, using createNewFile method, but it doesn't seem to work :(
This is pattern that do the saving, user can choose various types of image (bmp, jpeg ...):
imageFile is File
private void saveImage(){
JFileChooser savefile = new JFileChooser("~/");
savefile.setFileSelectionMode(JFileChooser.FILES_ONLY);//Chose file only
savefile.setFileFilter(new pngSaveFilter());//Save in PNG format
savefile.addChoosableFileFilter(new jpegSaveFilter());//Save in JPEG format
savefile.addChoosableFileFilter(new bmpSaveFilter());//Save in BMP format
savefile.addChoosableFileFilter(new gifSaveFilter());//Save in GIF format
savefile.setAcceptAllFileFilterUsed(false);
int returnVal = savefile.showSaveDialog(null);//Show save dialog
String EXT="";
String extension="";
if (returnVal == JFileChooser.APPROVE_OPTION) {
imageFile = savefile.getSelectedFile();
extension = savefile.getFileFilter().getDescription();
if (extension.equals("JPEG file images *.jpeg,*.JPEG")) {
EXT = "JPEG";
imageFile = new File(imageFile.getAbsolutePath() + ".jpeg");
}
if (extension.equals("PNG file images *.png,*.PNG")) {
EXT = "PNG";
imageFile = new File(imageFile.getAbsolutePath() + ".png");
}
if (extension.equals("Bitmap file images *.bmp,*.BMP")) {
EXT = "BMP";
imageFile = new File(imageFile.getAbsolutePath() + ".bmp");
}
if (extension.equals("GIF file images *.gif,*.GIF")) {
EXT = "GIF";
imageFile = new File(imageFile.getAbsolutePath() + ".gif");
}
try {
if(imageFile != null){
topViewImagePanel.drawToSave();
System.out.println(imageFile.createNewFile());
//ImageIO.write(topViewImagePanel.getSavingImage(), EXT, imageFile);
// the code detection is below
if (imageFile.createNewFile()){
int value = JOptionPane.showConfirmDialog(null, "Image existed! Replace?", "Warning!", JOptionPane.YES_NO_OPTION);
if (value == JOptionPane.YES_OPTION){
imageFile.delete();
ImageIO.write(topViewImagePanel.getSavingImage(), EXT, imageFile);
}else if (value == JOptionPane.NO_OPTION){
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
if(imageFile.exists())
Do a simple check to see if a file already exists or not.
Don't append file extension manually to the file name.
It is already present in the absolute path.
To handle files already present, use else clause of
if (imageFile.createNewFile())
Hope this helps.
If you use Java 7, use the new API:
if (imageFile != null) {
final Path path = imageFile.toPath();
if (Files.exists(path)) {
int value = JOptionPane.showConfirmDialog(null,
"Image existed! Replace?", "Warning!", JOptionPane.YES_NO_OPTION);
if (value == JOptionPane.YES_OPTION)
Files.delete(path);
}
ImageIO.write(topViewImagePanel.getSavingImage(), EXT,
Files.newOutputStream(path));
}
Also, as to your original question:
I put a detect code after the file is created, using createNewFile method, but it doesn't seem to work :(
This is normal, you call .createNewFile() twice:
System.out.println(imageFile.createNewFile()); // <-- CALL 1
//ImageIO.write(topViewImagePanel.getSavingImage(), EXT, imageFile);
// the code detection is below
if (imageFile.createNewFile()){ // <-- CALL 2
It will always fail the second time!

How to save the text file in a path given by JFileChooser?

I need to save a text File which is already created in a particular path given by JFileChooser. What I do basically to save is:
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
int status = chooser.showSaveDialog(null);
if (status == JFileChooser.APPROVE_OPTION) {
System.out.print(chooser.getCurrentDirectory());
// Don't know how to do it
}
How to save the text file in a path given by JFileChooser?
You want to add the following after if statement:
File file = chooser.getSelectedFile();
FileWriter fw = new FileWriter(file);
fw.write(foo);
where foo is your content.
EDIT:
As you want to write a text file, I'd recommend the following:
PrintWriter out = new PrintWriter(file);
BufferedReader in = new BufferedReader(new FileReader(original));
while (true)
{
String line = in.nextLine();
if (line == null)
break;
out.println(line);
}
out.close();
where original is the file containing data you want to write.
create a new File object with the path and name for the file
File file = new File(String pathname)
Try this:
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
int status = chooser.showSaveDialog(null);
if (status == JFileChooser.APPROVE_OPTION) {
FileWriter out=new FileWriter(chooser.getSelectedFile());
try {
out.write("insert text file contents here");
}
finally {
out.close();
}
}
// ...
You'll need the filename you want to save under in addition to the directory provided by chooser.getCurrentDirectory(), but that should do what you need it to. Of course, you'll need to write the save method that actually writes to the stream, too, but that's up to you. :)
EDIT: There's a much method to use, chooser.getSelectedFile(), that should be used here, per another answer in the thread. Updated to use that method.
EDIT: Since OP specified the file being written is a text file, I've added code to write the contents of the file. Of course, you'll need to replace "insert text file contents here" with the actual file contents to write.

Categories