• Post Reply Bookmark Topic Watch Topic
  • New Topic

Setting file name for JFileChooser Save dialog  RSS feed

 
m kamvar
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi--
I am wondering how to do the following:
when a user clicks on a save menu item, a save JFileChooser pops up. I would like to have a default file name set in the FileName box on the chooser, similar to what applications like Microsft word has. Right now, no file name will appear until the user has selected a file.
I also need to know how to get the text from this box in the case that the user enters a new file name (the getSelection function is not useful here because the user will not have selected an existing file.)
thanks for your help
mkamvar
 
Madhav Lakkapragada
Ranch Hand
Posts: 5040
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

"mkamvar"

your name doesn't agree with the javaranch guidelines. please
take a moment and re-register after reviewing the guidelines at http://www.javaranch.com/name.jsp
thanks for your cooperation.
- satya
 
Meghan Kamvar
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok- i changed my user name...
can anyone offer any helpful pointers on my question?
thanks
 
Nikki Parker
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have the same question and so far no one has been any help.
My last post was in July on this topic. Goodluck to you....my question still exists...hopfully someone will answer.
Nikki
 
Gregg Bolinger
Ranch Hand
Posts: 15304
6
Chrome IntelliJ IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, this can be done. The ony drawback is it has to be a File. You can't set the default name to a string. And, the file has to exist. But, if that is not a problem for you then just do this.
File f = new File("filename");
myJFileChooser.setSelectedFile(f);
And that puts the name of that file in the text area.
 
Meghan Kamvar
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for your help--
one more quick question.
if the user wants to modify the file name, how can i get the modified file name? is that possible?
thanks
 
Gregg Bolinger
Ranch Hand
Posts: 15304
6
Chrome IntelliJ IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not sure I understand that Question. What would you be using the file name for other than saving the file, which already happens. Do you need a String or what?
 
Meghan Kamvar
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sorry for the confusion, i will try to clarify my question.
In my application, i am trying to implement a "save file" function. So, when the user wants to save a file, i open the JChooser save dialog box with a defualt file (eg. file.dat) to save to selected.
However, I would like the user to be able to "save the file as.." If he wishes to save the document to a new file (and give the file a more descriptive name: eg, "graph.dat"), he can enter the file name to the File name box, and then my program can create a new file with the entered name. THis is where my problem arises- how can i get the entered name (a string) so that I can create and write to this new file?
thanks!!
 
Gregg Bolinger
Ranch Hand
Posts: 15304
6
Chrome IntelliJ IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I understand now.

JButton saveButton = new JButton("Save a File...", saveIcon);
saveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int returnVal = fc.showSaveDialog(FileChooserDemo.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile(); //This grabs the File you typed
Output Stream.write(file); // save the file.
}
}
});
 
alex earnshaw
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
my question is closely relating to this thread so I added a reply rather than started a new one, hope that's okay
I have something similar as above, ie a JFIleChooser where I have used setSelectedFile to set a default filename. However, my problem is that when the user selects a subdirectory of the directory the filechooser opened in, then the default filename I set is replaced by the name of the directory the user double-clicked on to open.
How can I get the file name I set e.g. 'default.txt' to remain in the 'File name' text box when the user is navigating through different directories? I only ever want the filename to change if the user edits it manually.
Hope you can help
Thanks
Alex
 
seema prakash
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I may be late for the reply. Here is the working code ...Hope it helps.



[ January 14, 2005: Message edited by: seema prakash ]
 
Joe Don
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have tried using this program to achieve similar solution to problem in GUI I'm building with NetBeans 8. But the outcome is that it neither shows error nor prove expected result; it's just dumb. Any further explanations?
 
Piet Souris
Rancher
Posts: 1984
67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hmmm... did you add this actionListener to a button? If so, can you show us your code?

Greetz,
Piet
 
Joe Don
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry for delay. I was out of town for a while. below is the code i used but it has not worked for. Besides, i am using it for creating an editor where i have "SAVE" and "SAVE AS". My challenge has been SAVE(). User should be able to save to an existing file. But where a file name already exists, user should be prompted. I am using netbeans 8/swing palete. Thanks forhelpin me.

 
Piet Souris
Rancher
Posts: 1984
67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Joe,

first of all: use the button 'code'. Select your code, and click that button.
If you want to do this by hand (as I think you did), then use the tags
[code[ = java]]...[/code] in stead of <code>...</code>.

Well, I flicked through your code, and at first glance, I can't find anything
wrong with it (apart from some strange looking code like


But my question was actually: does this code get invoked in the first place?
Do you invoke it when the button in question is clicked?

There are two easy ways to find out.
First: put a "System.out.println("...") at the very start of this code.
After clicking the button, you should then see this text appearing in the
output section of NetBeans.

Second method would be: set a breakpoint at the first line of the body
(click at the left of that line), and then use the option 'debug' in stead of
'run'. After you click the button, NetBeans should then stop at this line
(turning this line green), then you know that it gets invoked.

Greetz,
Piet
 
Campbell Ritchie
Marshal
Posts: 55772
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Piet Souris wrote: . . .
use the button 'code'. Select your code, and click that button.
If you want to do this by hand (as I think you did), then use the tags
[code[ = java]]...[/code] in stead of <code>...</code>. . . .
I have corrected the code tags for him. It is actually [code=java]…, slightly different from what you wrote.
 
Joe Don
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for the correction and attempt to resolve this problem. The basic challenge is that i can actually "SAVE AS" with the following code:



For the above chunk of codes, when i click my SAVE AS... button in my netbeans GUI, it actually saves as .txt file. But if i want to add more contents and save to an existing file, it does not work at all. Instead, it replaces the original content of the file. I am builfing a TEXT EDITOR, having in the FILE MENU the normal SAVE AS and SAVE buttons. All i am trying to resolve is the functionalities of these two methods in java. Please, while the bove code works for SAVEAS, can the folwing codes work for SAVE and at same time check if file already exists?




Thank you for understanding.
 
Piet Souris
Rancher
Posts: 1984
67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Joe,

first and formost: get the coding aligned! In its current form, it's impossible for me
to check if the code starting at line 38, is reached.
Aligning involves that opening and closing braces aare neatly aligned, and that
the code in between is indented.
Can you do that and show it to us?

Next: the code itself is pretty cluttered. I just noticed that it is the code from
seema prakash, from 2005. So it is pretty old.

The code starting at line 38 and ending at line 47 (I think) lookes okay to me.
The text should indeed be appended to whatever content there was.
Note that line 43 does NOT put a newline in the output, so next time
you run this code, the text "anotherString" will appear directly after
the end of the existing content. So maybe that's why you do not see
any new lines appearing?
Anyway, there is a lot of code following line 47, but I'll await your
aligned code first, to see what happens next.

Greetz,
Piet
 
Joe Don
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Basically, I am working on a java application and attempting to modify (or use outrightly)the code so that it no longer prompts the user with the dialog box to save a .txt file. The user already has the dialog box to choose a directoy in which to save the file at an early point within the application. That was what I referred to as save() and saveAs(). I came across the code in question on the coderanch platform in my search for a solution. Please, I would appreciate if the code could be modified to help me resolve this. I have been on this issue for so long a time now. I am still learning how to use the JFileChooser class and do not know much as yet. Please, kindly assist to modify and do not mind my errors. Thanks a lot because I trust Coderanch.
 
Piet Souris
Rancher
Posts: 1984
67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Joe,

no solution, but at least I reformatted the code, that will make all following replies
easier..

Now, if I understand you correctly: you have a menu, and two menu options within: 'Save' and 'Save As'.
You state that in an early stage there has already been a 'Save' action, and from that a filename
is known. Correct?

After that, it becomes unclear to me.

So, the user clicks 'Save'. Should whatever you want to be saved, be appended to the already saved
file, or should it overwrite it, or do you open a dialoge box to ask?

And when the user clicks: 'Save As', what then? Do you open a JFileChooser? And what about overwrite or append?

Please eplain this carefully. I do not think that a solution will be difficult, but I need to be sure I understand what
exactly needs to be done. Your last reply didn't make it clear, unfortunately.

And for now: I understand your feeling of impatience. But sometimes programming takes
more time than expected.

Anyway: for future coding issues, I put your code in NetBeans and pressed the format button.
 
Piet Souris
Rancher
Posts: 1984
67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Joe,

I just read in another topic (http://www.coderanch.com/t/586341/java/java/JfileChooser-save-dialog-box-popping),
that you are going to try some other ways. So I'll await these attempts.

Greetz,
Piet
 
Joe Don
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah! Please, follow me here to resolve this long standing problem; do not mind what you have read elsewhere. Sorry for my impatience.

To answer the following question (1):

"So, the user clicks 'Save'. Should whatever you want to be saved, be appended to the already saved file, or should it overwrite it, or do you open a dialoge box to ask?"

Answer:
(i) It should be appended to the already saved file.
(ii) But if no such file already exists, a dialog box should be opened.

To answer the following question (2):

"And when the user clicks: 'Save As', what then? Do you open a JFileChooser? And what about overwrite or append?"

Answer:
(i) When the user clicks "SAve As", it opens a JFileChooser.

(ii) It can only overwrites it if such file already exists. And this must be with a YES NO OPTIONS to give the user discretion (choices).

Note: I am building a text editor with necessary functionalities. Your idea of an editor like Notepad and how the "Save" and "Save As" buttons work will definitely give you a better understanding of what I am trying to achieve.

Thank you for your friendly and fatherly co-operation. Hear from you soon.
 
Piet Souris
Rancher
Posts: 1984
67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Joe,
okay.

Please note that the code I present has not been tested, since I only have these code snippets.
Can you give it a thorough inspection t see if it meets your demands?

Lets take on the first part. The user clicks 'Save' on the menu. Now, you've assured me that somewhere this has
already happened in a former reply. So I assume that from this first time SAVE, the file to which the content has
been saved, is known. For instance, it is stored in the member variable: File 'savedFile'.

So, lets assume that 'savedFile' is unequal to null.
Then all that remains to be done, is to write a method called 'appendToAlreadySavedFile' that does the appending.
So here goes:
We must use 'try', if only for the fact that the file may have been written to a USB stick that is no longer available.
Call this method in the ActionListener that belongs to the menu item 'SAVE' (or it may be a button that is used for this purpose).
You see, no need to open any JFileChooser here. However, it looks nice to report to the user that the SAVE action was succesfull,
or failed.

So, in the actionPerformed method, we should do something like


Greetz,
Piet
 
Joe Don
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Piet,
Thanks for your concern so far. But you are dealing with me as java professional whereas I'm yet to be one. It's been difficult working with the code. All I expected was how to make the user save (or add to) file in an already existing file in the same path WITHOUT SHOWING THE SAVE DIALOG BOX. This is common in all text editors. Just think of the SAVE and SAVE AS menu items in notepad, for example. How do they work if you want to save a file? I appreciate you once again. Cheers!
 
Piet Souris
Rancher
Posts: 1984
67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Joe,

I know what you mean, don't worry. And the code above was meant to do exactly that.
Just a click on a menu item, and without any popping up of whatever, the lot is saved.
It just seems nice to me to let the user know if th whole operation was indeed successful.
I gave an example of where it could go wrong, and the user better be aware of that.

However, having now a bit better insight, I must say: this is not going to be easy.
First of all, whatever code I may come up with, will have to fit somehow into the
existing code, and I have not seen any of that. The code from 2005, that I formatted,
is all I have to go by.
And secondly: it is not so easy to do an "append". The problem is: do you know what has
saved earlier, and do you know the new data that has to be appended?
I reckon that most programs, Notepad and the like, just overwrite the old file
with all the data; no appending at all, just brute rewriting. Not that I am sure of that,
but I wouldn't be surprised.

Is there any chance that you put the full code here?

Meanwhile, still thinking.

Greetz,
Piet
 
Joe Don
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Piet,
As a learning novice, it was a bit challenging to decipher the entire code.Remember I'm using netbeans'jButton/jMenuItem which has already initiated "private void actionPerform ...". So, there was no need for that in your code. With all sincerity, I think the best option to assist here is dragging a button into a GUI and run the code. This might solve a great deal. Thanks a lot. What a good associate you are!
 
Piet Souris
Rancher
Posts: 1984
67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Joe,

I use NetBeans myself, so I know what happens when you attach an ActionListener
to a menu entry or to a button.
Unfortunately, it doesn't at the same time add the code you need as well...

I have been rereading the replies in this topic since your first reply.
What comes to mind is that I would advise to include a third option, apart
from "Save" and "Save as", namely the option "Append to file".

For the first two options, I think the code works, I would just like them to
blindly overwrite an eventually existing file (after asking for confirmation, of course)
with the contents of your textfield.

Then, for the third option "Append to file", this very choice makes it immediately clear
that the user wants to append the text. We put a dedicated ActionListener in for that,
to keep the code less cluttered, and is easier to do than to put all the logic of these
three options in just one ActionListener.

How does that sound to you?

And yes, it is easy to check if the file that is returned from the JFileChooser exists or not.
In fact, this check is performed in the code. Look at the code that I formatted. It was my
reply from "7-8-2014 23:13:10", and in particular, line 28.

It says:

Now, why they do this in such a complicated manner, I don't know. The file that is returned
from JFileChooser is called 'theFile' (see line 24), so you could immediately do the test:

So, what about my proposition about this new option and a dedicated actionListener?

Greetz,
Piet
 
Joe Don
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please, why not test the code in netbeans, ensure it works before sending? I strongly believe you quite understand the case more than I; you can really resolve this while I learn how you arrive at the solution. Thanks
 
Piet Souris
Rancher
Posts: 1984
67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Joe,

I can't check this code in NetBeans. It is just a code snippet, an ActionListener,
and to test it, I need to build some application around it. But that would be my own
application, so that would be pretty useless.

That's why I asked you to supply me the full code, if at all possible. Thàt I can run.

So, can you put the code in here?

And, unfortunately, I am still unclear about what it is that you want.
As I understand it, you have a textarea, filled with text, that you want to save.
That's fine.

But then:

1)
the user, at a certain moment in time, will want to save it for the very first time.
It calls 'Save' from the menu/button, and your ActionListener code gets invoked.

Now, two possibilities:

a) the user gives a name of a file that does not exist. So, you create that file and write the full content of your textarea in it. Correct? If not, what must be done?

b) the user supplies a name of a file, and that file already exists. What now, do you want to overwrite that file, or do you want to append to it?

2)
the user wants to save the file, but the user has already saved that textarea before. Now what? Do you write the full contents of the textarea over that existing file
of the file that was used in the previously SAVE action? Or should it append to that file? (but in that case, you might get part of that textarea double). Note that in all these
cases you must store the name of that file that was used in the previous save action.

Or do you pop up another JFileChooser, and act as in possibility 1) ? If this doesn't apply, what then?

3)
And how does 'SAVE AS..' fit in the above scheme? Exactly the same?


Lastly, again about the append option: it is not always easy to determine what to append. For instance, the user types something into the textarea, saves it, and then
both appends new text AND changes the old text, all in one go. What would you like to "append" in such a case? The only viable option I see is to blindly overwrite
(or save to a new file) whatever there was before, with the complete contents of the textarea.


So, you see, I've supplied code that does a save without popping up a JFileChooser, but appending the text to some existing file.

My biggest problem is, as you can read, that I don't know exactly what you want to do. If you can clarify this, as best as you can, and supply me the
code of whatever you have so far, that would help enormously. Without this, I don't think I can be of any help.

Greetz,
Piet
 
Joe Don
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Piet,
You've got a good understanding to the solution. But I have already copied the code snippet here; don't forget, I got the snippet here too, hoping it might work in my application to my taste.
For purpose of emphasis, I will follow your outlines in the last post in my response.
(1) The user gives the name of file that does not exist. So, you create that file and write the full content of your textarea. This Correct.but don't forget this works with the SAVE AS button when no such file already exists.

(2) If the file already exists, it should be overwritten (only if user wants to re-save ( that is, save the existing file again, perhaps, with another name). This pops up dialog box to enable him do the needful as he desires.
(3) Additional content to the existing file (that is, EDITING the content of the existing file) should be append (and saved) but WITHOUT SHOWING THE SAVE DIALOG BOX. This because the user is only adding to or removing from existing file (editing). So, he does not want to overwrite or change the existing file. Just like othe TEXT EDITORS, this can only work with the SAVE BUTTON.
(4) SAVE AS button pops up dialog box in order to save FILE NOT ALREADY EXISTING. SAVE button appends (and saves) to already existing file in the case of editing the file but without popping up dialog box. However, SAVE button can only POP UP DIALOG BOX IF SUCH FILE IS BEING SAVED FOR THE VERY FIRST TIME.

With your good knowledge of how TEXT EDITORS work, I do hope you quite understand the submission now. Thanks a lot for your concern. Cheers.
 
Piet Souris
Rancher
Posts: 1984
67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Joe,

allright. Since I have no code to test, I will write a small application (well, as small as I can),
where I have a JTextArea, two buttons and a menu bar, and an actionlistener that will, as
much as I understand, do everything you just wrote.

The intention is that you look at my code, and see what I am doing. If that is close enough
to your specifications, then you can use it in your own program. I will try to write it in an
as clear as possible way, and add full comments, so that you will have no trouble in following it.

The reason I follow this route is that I need some way of knowing when a SAVE is a 'first' SAVE,
or not. Since I do not know your application, I can;t tell you how to do that, and maybe you
have already something for that.

It will take me some time, but "I'll be back".

Greetz,
Piet
 
Joe Don
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot. I suppose you use jButtons or jMenuItems (well, if you deem it fit) from the palette of netbeans since I'm using that for now. Once again, thanks.
 
Piet Souris
Rancher
Posts: 1984
67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hihihi...

Yes, I will use NetBeans for the Layout, and for adding the buttons and the menubar,
and possibly including that horroble code that deals with the GroupLayout.
Do you have any preference for the LayoutManaget to use?

Greetz,
Piet
 
Joe Don
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not really because I use the JFrame from within Netbeans, if that's what you refer here.
 
Piet Souris
Rancher
Posts: 1984
67
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Joe,

as promised.

I wrote a simple application in which the policy concerning save actions
plays a central role.

It may not be in the form you expected, but my intention is only to
show how one can implement the save actions that you wrote about.
The only thing that was, and still is, very vague to me is the 'append'
question. So I added another buuton and menu item for this sole
purpose. It makes it much more clear to a user.

I tried to document everything, so it will be easy for you to follow and
adjust or replace anything as you see fit.

I used the NetBeans GUI Builder, as you wanted. The package name
is 'JoeDon', so create a new project under this name, and copy the two
files into it.

Greetz,
Piet

PS: @#$%^&. This forums code editor leaves out some underscores.
So if you get errors in NetBeans, check if you see any spaces that
look suspicious. If so, put an underscore in place of that space.
For instance, I have a variable called 'menu_Save'. If you see it
as 'menu Save', then that is where you must insert this underscore.

 
Joe Don
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok. As soon as I go through, I will get back here. Thanks a lot.
 
Joe Don
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great work! It works correctly. The "append button" wasn't even necessary but "save" and "save as". You have thought me a great deal. Thanks a lot, Piet, and keep it up. How can one contact you privately? Email or what?
Cheers!

Joe
 
Rob Spoor
Sheriff
Posts: 21095
85
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Joe Don wrote:How can one contact you privately? Email or what?

Please UseTheForumNotEmail. Once you start emailing everything will become private, and others cannot learn from anything that is said.
 
Joe Don
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok then
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!