I'm trying to allow the user to either select an already created .ser file and save over it, or create a new .ser file by typing in a new name in the JFileChooser textfield. As you can see from the code below, I used a if/else statement to determine which of the two the user is doing. The problem I'm experiencing is that no matter how I rearrange things, or use different if conditions, the JFileChooser always chooses the latter option (create a new .ser file by typing in a new name). This wouldn't be a big problem, but it always adds ".ser" to the file.
For example: If I create a new file in JFC called mySERObject, it will be saved as "mySERObject.ser." Now when I open JFC again, and I select with my mouse mySERObject.ser, to save over, it instead creates a new file called "mySERObject.ser.ser."
I uses the System.out.println to see which statement gets exected, and it's always the "First one printed." Here's my code:
private void addSaveAsListener(JMenuItem item) {
item.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
JFileChooser fc = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"Serialized Object Files", "ser", ".ser");
fc.setFileFilter(filter);
final JTextField textField = getTextField(fc); //gets text from JFC textfield
int returnVal = fc.showSaveDialog(null);
String fileName = textField.getText();
if (returnVal == JFileChooser.APPROVE_OPTION) {
if (!(fc.getSelectedFile().length() > 0)) {
System.out.println("first one printed");
File file = new File(fc.getCurrentDirectory(), fileName
+ ".ser");
try {
file.createNewFile();
fileSystem.saveAs(addressbook.getCopyList(), file.getAbsolutePath()); //serializes arraylist
} catch (IOException e) {
JOptionPane.showMessageDialog(null,
"File unable to be created.");
}
} else {
String path = fc.getSelectedFile().getAbsolutePath();
fileSystem.saveAs(addressbook.getCopyList(), path); //serializes arraylist
System.out.println("2nd one printed");
}
}
}
});
}
I was wondering if you could help me with what's wrong or by offering solutions, thank you.
Question 1: There is always another suffix added, what can I do?
Look at the following code from your example. You will see, that you get the textfield from the fc, then get the string from that (aka "mySERObject.ser") and then you gone save again, with ".ser" appendig. You can maybe use some String opperations on fileName to get rid of the suffix before further processing (for example with fileName.replace(".ser", "")).
final JTextField textField = getTextField(fc);
String fileName = textField.getText();
//fileName.replace(".ser", "")
File file = new File(fc.getCurrentDirectory(), fileName + ".ser");
Question 2: In my if/else block only if clause will be selected. Why?
I personally don't know much about JFileChooser, but fc.getSelectedFile().length() seems not to work like you think, since it always returns 0. But you can just use fileName.length(), can't you?
Related
I'm creating a Guess Who game as an independent final project for my object-oriented university class and was running into an issue. One of the things I want my program to be able to do is let the user upload his/her own files from the computer to be used in the guess who game. Basically, the user clicks a JRadioButton and then the FileChooser box will open so he/she can navigate to the folder with the files. I realize that you can use the setMultiSelectionEnabled(true) command to make it so that you can select multiple files, but is there a way that I can restrict the selection to only 25 images (the size of my game-board)? Is there an easier way of doing this? Should I just make it so that the user can only select folders filled with images?
The reason I want the specific files is because I want to load the images into an ImageIcon array and the names of the files (before the extensions), into an array as well.
Here is the code I have so far:
private class fileSelector implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JFileChooser files = new JFileChooser(); //creates a new filechooser
files.setCurrentDirectory(new File(System.getProperty("user.home"))); //starts the filechooser at the home directory
FileNameExtensionFilter filter = new FileNameExtensionFilter("*.Images", "jpg", "png", "gif"); //only allows files with these extensions to be used
files.addChoosableFileFilter(filter); //adds the filter
files.setMultiSelectionEnabled(true); //makes it so you can select multiple files!
files.showOpenDialog(null);
}
}
Any help would be great! Thanks!
sadly their is no way to do this cause this is ComponentUI related !
#trashgod made great examples here
also you can make an FileFilter like this
public class ImagesFilter extends FileFilter {
#Override
public boolean accept(File f) {
if (f.isDirectory()) {
File[] list = f.listFiles();
if (list.length == 25) {
boolean ret = true;
for (File file : list) {
ret = ret && isMyImageType(file);
}
return ret;
}
}
return false;
}
#Override
public String getDescription() {
//descripe it .
return "";
}
}
and then later in the JFileChooser.getIcon(File f) override it to get a special icon that suits your project with the same class like :-
private final ImagesFilter filter = new ImagesFilter();
#Override
public Icon getIcon(File f) {
if (filter.accept(f))
{
//return your icon
}
return super.getIcon(f); //To change body of generated methods, choose
}
When you want to do something when a component changes (an event takes place), use a PropertyListener. Every time a user changes his selection an event is taking place. You can add a property listener to your file chooser and check if he has selected more files than you want.
Take a look at this example (max files 2):
JFileChooser files = new JFileChooser(); // creates a new filechooser
files.setCurrentDirectory(new File(System.getProperty("user.home"))); // starts the filechooser at the home
// directory
FileNameExtensionFilter filter = new FileNameExtensionFilter("*.Images", "jpg", "png", "gif"); // only allows
// be used
files.addChoosableFileFilter(filter); // adds the filter
files.setMultiSelectionEnabled(true); // makes it so you can select multiple files!
files.addPropertyChangeListener(e -> {
File[] selectedFiles = files.getSelectedFiles();
if (selectedFiles.length > 2) {
File[] selectedFilesNew = new File[2];
// Select the first 2
for (int i = 0; i < selectedFilesNew.length; i++) {
selectedFilesNew[i] = selectedFiles[i];
}
files.setSelectedFiles(selectedFilesNew);
JOptionPane.showMessageDialog(files, "Only 2 selected files allowed.", "File chooser",
JOptionPane.ERROR_MESSAGE);
}
});
files.showOpenDialog(null);
Rembember though, that this is a file count restriction and not a folder count restriction.
I'm creating a program which will create files with different extensions. For that, i'm using the JFileChooser. I've set the FileFilter to accept only my desired extensions, but when I select one, I still have to add the extension in the name of the file myself. How can I solve that? Many thanks!
You basically have to add the extension yourself after the user closes the dialog.
This example allows the user to specify a file ending with ".foo" or ".bar" and will add that extension if the user did not do so.
JFileChooser fileChooser = new JFileChooser();
fileChooser.setMultiSelectionEnabled(false);
fileChooser.removeChoosableFileFilter(fileChooser.getAcceptAllFileFilter());
fileChooser.setFileFilter(new FileNameExtensionFilter("Files ending in .foo", "foo"));
fileChooser.setFileFilter(new FileNameExtensionFilter("Files ending in .bar", "bar"));
int option = fileChooser.showSaveDialog(null);
if (option == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
if (file!=null) {
FileFilter fileFilter = fileChooser.getFileFilter();
if (fileFilter instanceof FileNameExtensionFilter && ! fileFilter.accept(file)) {
// if the filter doesn't accept the filename, that must be because it doesn't have the correct extension
// so change the extension to the first extension offered by the filter.
FileNameExtensionFilter fileNameExtensionFilter = (FileNameExtensionFilter) fileFilter;
String extension = fileNameExtensionFilter.getExtensions()[0];
String newName = file.getName() + "." + extension;
file = new File(file.getParent(), newName);
}
System.out.println("The selected file is: " + file.getAbsolutePath());
}
}
For that you have to get the filefilter selected by the user after he presses the validating button of the JFileChooser and compare the filefilter description with the list of your extensions before initializing the file object with the specified extension in your code if there is a match. I don't know if you will understand me.
Modelexcel model = new Modelexcel();
JFileChooser selectFile = new JFileChooser();;
File file;
JButton btnExporterVersExcel = new JButton("Exporter vers Excel");
btnExporterVersExcel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(selectFile.showDialog(null, "Exporter")==JFileChooser.APPROVE_OPTION) {
String extension=selectFile.getFileFilter().getDescription();
if(extension.contains("(*.xlsx)")) {
file= new File(selectFile.getSelectedFile()+".xlsx");
}else if(extension.contains("(*.xls)")){
file= new File(selectFile.getSelectedFile()+".xls");
}
if(file.getName().endsWith("xls") ||
file.getName().endsWith("xlsx")) {
JOptionPane.showMessageDialog(null, model.Export(file, table));
}else {
JOptionPane.showMessageDialog(null, "Format invalid");
}
}
}
});
This is a fragment of my code to save files in ".xls" and ".xlsx" formats. Hope a look through it will help you
I'm trying to make a program that asks the user for information and then when they click save, the text boxes and labels and all are saved into a file to be able to be shared. It could be any type of file if need be. The information is in a Tabbed pane inside a JFrame. Here is my current save method.
FileFilter ft = new FileNameExtensionFilter("Text Files", "txt", "jpg","png", "jpeg");
db.addChoosableFileFilter(ft);
int returnVal = db.showSaveDialog(this);
if (returnVal == javax.swing.JFileChooser.APPROVE_OPTION) {
java.io.File saved_file = db.getSelectedFile();
String file_name = saved_file.toString();
try {
WriteFile data = new WriteFile(file_name, false);
String allText = JFrame.toString(); //Line im having trouble with
data.writeToFile(allText);
} catch (java.io.IOException e) {
System.out.println(e.getMessage());
}
}
JFrame.toString wont give you any state that you want to save.
The right approach is to get each value from text boxes and save/reload manually into a file.
Another approach that you can try, is to serialize the whole JFrame into a file. Look at this JavaDoc for more info.
I am currently working on a "Notepad - type" file for my Object-Oriented Java class. I've got most of the program done - however I am stuck on the following issue:
When the program tries to save a file, it is supposed to first check for a files existence, obviously if the file exists the program will prompt the user for permission to overwrite the existing copy of the file [The overwrite prompt is not written yet, but it will go in the if(selectedFile.exists() == true) portion of code] - and if the file does not exist, the program will create it.
The issue I am having is that the program always creates the file before checking for the files existence. I have looked at probably 20-30+ answers to similar questions - mainly on stackoverflow, and have yet to come across the answer i need. I'm not sure if I am just "not getting it", or if I have really done something wrong..
Any answer - or hint as to where to find the answer - to this issue would be greatly appreciated.
Thank You.
Complete code (for the save portion of the program is shown below).
else if(source == saveFile)//-------------------------//SAVE FILE//--------------------------
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
fileChooser.setDialogTitle("JavaPad - Save File");
int result = fileChooser.showSaveDialog(fileChooser);
String myFile;
try
{
if(result == JFileChooser.APPROVE_OPTION)
{
myFile = fileChooser.getSelectedFile().getName();
File selectedFile = new File(myFile);
String[] lines = textArea.getText().split(System.getProperty("line.separator"));
readToSave = new Scanner(lines.toString()); // CANNOT use toString() on an Array - THIS WILL BE CHANGED PROPERLY?
PrintWriter savePWriter = new PrintWriter(selectedFile);
if(selectedFile.exists() == true)
{
JOptionPane.showMessageDialog(null, "This file already exists.");
statusLabel.setText("File Save Aborted...");
}
else
{
System.out.println("Creating File: " + myFile);
File newFile = new File(fileChooser.getSelectedFile().getName());
savePWriter = new PrintWriter(newFile);
int i = 0;
while(i < lines.length)
{
savePWriter.append(lines[i] + "\n");
System.out.println("Lines appended = " + i);
i++;
}
savePWriter.flush();
savePWriter.close();
statusLabel.setText("File Saved.");
}
}
else
{
JOptionPane.showMessageDialog(null, "Save has been canceled.");
}
}
catch(IOException IOSaveError)
{
System.out.println(IOSaveError);
}
}
You are calling new PrintWriter(selectedFile), which creates the file, right before you check whether selectedFile exists.
Don't create the PrintWriter before checking if the file exists. The PrintWriter is what causes the file to be written to.
You do:
myFile = fileChooser.getSelectedFile().getName();
File selectedFile = new File(myFile);
PrintWriter savePWriter = new PrintWriter(selectedFile); // Creates File! Probably unwanted.
if(selectedFile.exists() == true) // always true because of the line above
By the way, your code is far too complicated. Instead of having the variables selectedFile and newFile, which both are newly created File objects, you could simply use the File object returned by the dialog: newFile = fileChooser.getSelectedFile().
if(selectedFile.exists() == true)
can be simplified to
if (selectedFile.exists())
I recommend to do I/O using try-with-resources whenever possible:
try (final PrintWriter writer = new PrintWriter(selectedFile)) {
// Use writer
}
This helps with accidentally forgetting to close streams.
I have 2 classes one of which is a GUI.
My first class is called MusicSearch.java and it has this:
public static void directoryMusicLocator(File dir) {
try
{
String[] filetype = new String[] { "mp3" }; // only search mp3 files
System.out.println("Getting all .mp3 files in " + dir.getCanonicalPath() + " including those in subdirectories");
List<File> files = (List<File>) FileUtils.listFiles(dir, filetype, true);
for (File file : files)
{
System.out.println(file.getAbsolutePath()); // get the file's absolute path
}
System.out.println("\nFinished Searching.");
}
catch (IOException e)
{
e.printStackTrace();
}
}
What this does is that it searches for Mp3 files on a directory for example C:\Music
For the GUI, well I created it using netbeans' JFrame Designer and a screenshot of this can be seen on the image below. (I can't embed images at the moment so I can only provide a link to the image.)
http://i.stack.imgur.com/7pLPL.jpg
On the JTextField next to the "Enter Location", the user enters a location for example C:\Music. When the user clicks the button "Find MP3's" the method directoryMusicLocator is called. Below is the Action Listener for the Find MP3's button:
private void findMP3ButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String fLocation = dirToSearch.getText(); // this gets the input from the textfield
File dir = new File(fLocation); // converts the location to path
MusicSearch.directoryMusicLocator(dir);
}
An example of the output can be seen below when it is ran and user entered C:\Music on the textfield:
C:\Music\Feint - Times Like These (Fracture Design Remix).mp3
C:\Music\Ficci - Climax (FREE).mp3
C:\Music\Ficci - Making Me Blue (FREE).mp3
Now what I want is the output to display on the JTextArea but I don't know how. Can someone tell me how.
Thanks
You just have to do the following changes in your directoryMusicLocator and findMP3ButtonActionPerformed methods. Instead of directly printing you just need to store the content in a StringBuilder and return that so that you can show it in the JTextArea.
public static String directoryMusicLocator(File dir) {
try
{
String[] filetype = new String[] { "mp3" }; // only search mp3 files
StringBuilder outString = new StringBuilder("Getting all .mp3 files in " + dir.getCanonicalPath() + " including those in subdirectories\n");
List<File> files = (List<File>) FileUtils.listFiles(dir, filetype, true);
for (File file : files)
{
outString.append(file.getAbsolutePath()+"\n"); // get the file's absolute path
}
outString.append("\nFinished Searching.");
return outString.toString()
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
}
private void findMP3ButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String fLocation = dirToSearch.getText(); // this gets the input from the textfield
File dir = new File(fLocation); // converts the location to path
String output = MusicSearch.directoryMusicLocator(dir);
// Replace <jTextArea> with your JTextArea field name
<jTextArea>.setText(output);
}
JTextArea textArea = new JTextArea(); // instantiate the JTextArea
textArea.append("text"); // append to the existing text on JTextArea
textArea.setText("text"); // set the current text with the given one
hope this helps :)
Rather than calling System.out.println, which sends the output to the standard output steam, you should send it to the text area. But you can't do that without a reference to the JTextArea that you're working with, so you need to change the signature of directoryMusicLocator to include a JTextArea like so:
public static void directoryMusicLocator(File dir, JTextArea outputTextArea) {
Then, you'll want to change System.out.println(newText) to outputTextArea.append(newText + System.getProperty("line.separator")). (Replace "newText" with the parameters that you're sending to the JTextArea.
Finally, change the call-sites for directoryMusicLocator(File) - pass a reference to the JTextArea: MusicSearch.directoryMusicLocator(dir, jTextArea1)