Require a simple save option

hi

in my java menu, i have a save option that saves the contents of a JTextArea to a .txt file

at the moment, im not using showSaveDialog() so the file is just getting saved under a name that i specificed in the code!

but now i want the option of selecting the directory or folder in which to save the .txt file.

this needs to be very simple and kept in one class.

so again heres what i want:

user be able to type in a few lines into JTextArea,
select save from menubar or button on screen,
pops up savedialog,
user selects dir or folder and clicks save!

this is urgent and only fully working code with be awarded 500 points +

as more questions to come but need this working first...

cheers

sean
LVL 16
ellandrdAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

zzynxSoftware engineerCommented:
>> only fully working code
We're here to help you with code that you wrote, not to provide full blown solutions (against the EE rules)

Have a look at http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JFileChooser.html
0
zzynxSoftware engineerCommented:
0
ellandrdAuthor Commented:
ok maybe i didnt explain it correct "fully working code"

ill post my code later cos right now i havnt code my code on the computer im using.

i get error when i try called showsavedialog() thats why i asked for code as answers to compare it to mine!

ill post my error message and code later if that helps....

sean
0
Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

shah1d1698Commented:
Following site might come for some help...it describes how to use JFileChooser to create an open-file dialog and a save-file dialog....

http://www.javaalmanac.com/egs/javax.swing.filechooser/CreateDlg.html
0
shah1d1698Commented:
ooooooooooooo....zzynx has already posted it..... :-(
0
zzynxSoftware engineerCommented:
>> i get error when i try called showsavedialog()
The link in my 2nd comment should help you.
If not let us know your problem.
0
ellandrdAuthor Commented:
id post the code if i have the code on my computer at the time of asking.

sorry for the way ive explained my question as i take it, everyone thinks its an assignment?!

i was planning to post my code when i was able to!

plus i had other questions relating to other problems and that why i said 500 + points up for grabs...

maybe i should rethink in how i write my questions in the future....

anyways if ye are helping heres my code and waht ive do in terms of saving to txt file so far:

actionlistener part for save button
--------------------------------------------
buttonSave = new JButton("Save");
        buttonSave.setFont(new Font("Trebuchet MS", Font.BOLD, 12));
       
        buttonSave.addActionListener( new ActionListener()
        {
            public void actionPerformed( ActionEvent e)
            {
                ApplicationGUI.this.save();
            }
        } ) ;
        this.getContentPane().add(buttonSave);



ApplicationGUI.this.save part
----------------------------------------
public void save()
    {
        try
        {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("C:\\JavaGUICode\\Results.txt"));
            String text = textareaOutput.getText();
            bos.write(text.getBytes());
            bos.flush();
            bos.close();
        }
        catch (IOException ioe)
        {
            JOptionPane.showMessageDialog( this , ioe.toString() , "Saving Error" , JOptionPane.YES_OPTION);
        }
    }        

now instead of just saving when a save button is clciked i wnat a savedialog window to appear...

need help getting this working as i get errors

i have taken out the showsavedialog code but will add it again, if you wnat to see where im going wrong??

thank you
0
zzynxSoftware engineerCommented:
>> now instead of just saving when a save button is clciked i wnat a savedialog window to appear...
I think the links I posted are very helpful for that.

>> need help getting this working as i get errors
It would be handy if you
1) post the code you have errors with
2) tell us *what* errors you have
0
ellandrdAuthor Commented:
well ive looked at them and i had no success

be right back with my code:

0
ellandrdAuthor Commented:
menubar item code

 mi = new JMenuItem( "Save" ) ;
        mi.setFont(new Font("Trebuchet MS", Font.BOLD, 14));
        mi.addActionListener( new ActionListener()
        {
            public void actionPerformed( ActionEvent e)
            {
                fc.showSaveDialog(this);
                File file = fc.getSelectedFile();
                ApplicationGUI.this.save(file);
            }
        } ) ;
        file.add( mi ) ;



save method which is also in the same class ApplicationGUI:
 public void save(File f)
    {
        try
        {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f));
            String text = textareaOutput.getText();
            bos.write(text.getBytes());
            bos.flush();
            bos.close();
        }
        catch (IOException ioe)
        {
            JOptionPane.showMessageDialog( this , ioe.toString() , "SolReSol Translator Saving Error" , JOptionPane.YES_OPTION);
        }
    }


error message:

 ApplicationGUI.java [67:1] showSaveDialog(java.awt.Component) in javax.swing.JFileChooser cannot be applied to (<anonymous java.awt.event.ActionListener>)
                fc.showSaveDialog(this);
                  ^
1 error
Errors compiling ApplicationGUI (->).

see what i mean??

thanks
0
zzynxSoftware engineerCommented:
>> see what i mean??
Now, I *do* see it yes, while before I didn't.

you pass "this" as parameter to showSaveDialog().
Apparently "this" references to your anonymous ActionListener.
You should pass your main JFrame instance. (You could even try passing null, if you don't have that one)
Try it and let me know.
0
ellandrdAuthor Commented:
ok this fixed the errors but when i select the save button, nothing happens??

any ideas why??

is my code correct??
0
zzynxSoftware engineerCommented:
>> ok this fixed the errors but when i select the save button, nothing happens??
What did you eventually pass as parameter?

>>is my code correct??
Can you show the creation code of variable fc (JFileChooser)?
0
ellandrdAuthor Commented:
i passed the Jframe instance "frame" as parameter.

ive declared JFileChooser fc as private

heres my code

import java.awt.*;
import java.io.File.*;
import javax.swing.JFileChooser.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JOptionPane;
import java.awt.Color.*;
import java.io.*;
import java.util.*;
import java.text.*;

public class ApplicationGUI extends JFrame
{
    private JFrame frame;
    private JTextArea textareaOutput;
    private JScrollPane sp_textareaOutput;
    private JButton buttonSave;
    private JFileChooser fc;
   
    public ApplicationGUI(Dictionary d)
    {
        guiLayout customLayout = new guiLayout();
        this.getContentPane().setLayout(customLayout);
       
        JMenuBar mb = new JMenuBar() ;
        this.setJMenuBar( mb ) ;
        JMenuItem mi ;

        JMenu file = new JMenu( "File" ) ;
        file.setFont(new Font("Trebuchet MS", Font.BOLD, 14));
        mb.add( file ) ;

        mi = new JMenuItem( "Save" ) ;
        mi.setFont(new Font("Trebuchet MS", Font.BOLD, 14));
        mi.addActionListener( new ActionListener()
        {
            public void actionPerformed( ActionEvent e)
            {
                fc.showSaveDialog(frame);
                File file = fc.getSelectedFile();
                ApplicationGUI.this.save(file);
            }
        } ) ;
        file.add( mi ) ;

        textareaOutput = new JTextArea("");
        sp_textareaOutput = new JScrollPane(textareaOutput);
        this.getContentPane().add((sp_textareaOutput));


        buttonSave = new JButton("Save");
        buttonSave.addActionListener( new ActionListener()
        {
            public void actionPerformed( ActionEvent e)
            {
                fc.showSaveDialog(frame);
                File file = fc.getSelectedFile();
                ApplicationGUI.this.save(file);
            }
        } ) ;
        this.getContentPane().add(buttonSave);

        this.setSize(getPreferredSize());

        addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent e)
            {
                ApplicationGUI.this.exit();
            }
        });
    }
   
    public void save(File f)
    {
        try
        {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f));
            String text = textareaOutput.getText();
            bos.write(text.getBytes());
            bos.flush();
            bos.close();
        }
        catch (IOException ioe)
        {
            JOptionPane.showMessageDialog( this , ioe.toString() , "SolReSol Translator Saving Error" , JOptionPane.YES_OPTION);
        }
    }



        private void exit()
    {
        // asks user if he/she are sure to exit
        if ( JOptionPane.showConfirmDialog( null , "Are you sure you want to quit?" , "Exit" , JOptionPane.YES_NO_OPTION) == 0 )
            System.exit( 0 ) ;
    }
}    

thats all my class code!

thanks

0
ellandrdAuthor Commented:
when i click on the save button, here is the error in the output window of netbeans 3.6

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
        at ApplicationGUI$15.actionPerformed(ApplicationGUI.java:244)
        at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
        at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
        ....
        ....

plus everytime i compile my class a new file "ApplicationGUI$15" is created! like above in the error message...

why is this?  it never used to happen when i used to use other java software kawa pro 5.0...


0
zzynxSoftware engineerCommented:
Try these changes:

        mi = new JMenuItem( "Save" ) ;
        mi.setFont(new Font("Trebuchet MS", Font.BOLD, 14));
        final JFrame thisFrame = this;                                       // <<<<<<< add this
        mi.addActionListener( new ActionListener()
        {
            public void actionPerformed( ActionEvent e)
            {
                fc.showSaveDialog(thisFrame);                // <<<<<<<< pass thisFrame
                File file = fc.getSelectedFile();
                ApplicationGUI.this.save(file);
            }
        } ) ;
        file.add( mi ) ;

       textareaOutput = new JTextArea("");
        sp_textareaOutput = new JScrollPane(textareaOutput);
        this.getContentPane().add((sp_textareaOutput));

        buttonSave = new JButton("Save");
        buttonSave.addActionListener( new ActionListener()
        {
            public void actionPerformed( ActionEvent e)
            {
                fc.showSaveDialog(theFrame);                   // <<<<<<<< pass thisFrame
                File file = fc.getSelectedFile();
                ApplicationGUI.this.save(file);
            }
        } ) ;
        this.getContentPane().add(buttonSave);
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ellandrdAuthor Commented:
also when i first complied it this is what the note i get in netbeans:

Note: C:\Documents and Settings\Sean Delaney\Desktop\ApplicationGUI.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Finished Project Default.

Any ideas about this one??

sorry for attacking you with questions but i finish my work soon and wont be back till tomorrow...

thanks again
0
ellandrdAuthor Commented:
no still getting these errors when i click save

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
        at ApplicationGUI$15.actionPerformed(ApplicationGUI.java:246)
        at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
        at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
     

i think its got to do with the "ApplicationGUI$15" being created but i dont know who to fix this or what is causing this??

plus the fact im only started using netbeans to program in java...

0
zzynxSoftware engineerCommented:
>> Any ideas about this one??
It is what it says: you use somewhere in your ApplicationGUI.java file a deprecated function.
But I don't see at first sight what it could be.
You can recompile with some option to have more details about it.
0
ellandrdAuthor Commented:
so is that why more files are being created and named as applicationGUI$1 to applicationGUI$15 everytime i compile it?
0
zzynxSoftware engineerCommented:
Of course!
You nowhere initialized "fc", do you?

Replace

>> private JFileChooser fc;

by

 private JFileChooser fc = new JFileChooser();
0
zzynxSoftware engineerCommented:
>> is that why more files are being created and named as applicationGUI$1 to applicationGUI$15 everytime i compile i
I really don't know that one. (Although I'm using netBeans everyday)
0
ellandrdAuthor Commented:
i havnt add the layout manager code that i used in this class!

i left it out when posting the question as i takes up spaces...

ill post it if you want??
0
zzynxSoftware engineerCommented:
>> i havnt add the layout manager code that i used in this class
Not needed, so far.
0
VenabiliCommented:
>> is that why more files are being created and named as applicationGUI$1 to applicationGUI$15 everytime i compile i
Yep - this is the inner class. I usually delete all the classes from time to time to recreate the classes from teh beginning :)
0
ellandrdAuthor Commented:
right i think i kinda found an answer to why its creating file named application$1 to 10 everytime...

ive used a java gui builder to build my gui and copied the code from that into netBeans

in my layout manager code, its adding all the componments to the frame and for each component a new file named applicationGUI$3 for example is created!

i saw this as i commented out all the components except the save button and textarea and it only created two extra files called applicationGUI$0 and applicationGUI$1.

then i uncommented another compoment and recompiled and found that it created a third file called applicationGUI$2...

any ideas of how i overcome this?

create a gui not using the java gui builder?
0
zzynxSoftware engineerCommented:
So, for every compile a new file is added when there's an inner class in the code?
Mmm. Good to know Venabili.
0
zzynxSoftware engineerCommented:
What about

        private JFileChooser fc = new JFileChooser();

ellandrd?

0
ellandrdAuthor Commented:
ok i added JFileChooser fc = new JFileChoose(); and it fixed the problem of not opening the savedialog, but no if i select cancel i get these errors:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
        at java.io.FileOutputStream.<init>(FileOutputStream.java:172)
        at java.io.FileOutputStream.<init>(FileOutputStream.java:131)
        at ApplicationGUI.save(ApplicationGUI.java:346)

and netBeans points to my save method:

public void save(File f)
    {
        try
        {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f)); <<<<< this line???
            String text = textareaOutput.getText();
            bos.write(text.getBytes());
            bos.flush();
            bos.close();
        }
        catch (IOException ioe)
        {
            JOptionPane.showMessageDialog( this , ioe.toString() , "SolReSol Translator Saving Error" , JOptionPane.YES_OPTION);
        }
    }
0
ellandrdAuthor Commented:
ok Venabili how do i overcome this from happening?

cos when i use to use kawapro5.5 for building java application this used never happen...

and its abit annoying now!

any ideas why i kkep getting errors when selecting cancel on savedialog??

thanks

0
ellandrdAuthor Commented:
can i just take out my layout class thats within the applicationGUI class and use it as a separate class instead??
0
zzynxSoftware engineerCommented:
saveShowDialog()
Returns:
the return state of the file chooser on popdown:
JFileChooser.CANCEL_OPTION
JFileChooser.APPROVE_OPTION
JFileCHooser.ERROR_OPTION if an error occurs or the dialog is dismissed

You have to capture that one:

   int result = fc.showSaveDialog(theFrame);                  
   if (result.JFileChooser.CANCEL_OPTION )
      return;

Or you could also replace

    >>ApplicationGUI.this.save(file);
by
       if (file!=null)
          ApplicationGUI.this.save(file);

That's called "defensive programming" ;°)
0
VenabiliCommented:
>> So, for every compile a new file is added when there's an inner class in the code?
Mmm. Good to know Venabili.

I had to write it more clear... Actually the normal is to create one such class for every inner clas....

BUT if you just recompile - without rebuilding (or whatever it is -- I mean not to delete all classes before the compile but compiling only the changed ones), these numbers grow... I hope I explained it better this time...

ellandrd ,

Using GIU manager makes a lot of inner classes IMHO. I usually write the code myself so I am sure what's going on in it.
What mistakes you receive?

Venabili

0
ellandrdAuthor Commented:
ok ive now got another error

 int results = fc.showSaveDialog(theFrame);                  
   if (results.JFileChooser.CANCEL_OPTION )
      return;

ApplicationGUI.java [248:1] int cannot be dereferenced
                if (results.JFileChooser.CANCEL_OPTION )
                           ^

sorry guy, my 'debugging head' is at home....
0
zzynxSoftware engineerCommented:
My fault. That was a typo. Should be of course:

if (results == JFileChooser.CANCEL_OPTION )
0
ellandrdAuthor Commented:
i would write the code myself for the gui, but my gui is very complex and i cant get my layout the way i want it, so using a gui builder, i can achieve the layout that i require...

if im creating small gui, i write the code my self, but this gui is to be the full size of the screen and i cant seem to get the layout working correct...

i solved the problem if the user cancels the save option.
0
zzynxSoftware engineerCommented:
>> i solved the problem if the user cancels the save option
Good!
Anything else?
0
ellandrdAuthor Commented:
right so correct me if im wrong?

remember im new to netbeans

so if i just recompile and run another file will be created from the inner class?!

so have i to rebuild then recompile then run and this will stop the file being created from the inner class??
0
ellandrdAuthor Commented:
just wanna make sure that what i wrote above is causing the extra file to be created??

will award you the points in a minute....

thank you ever so much!!

sean
0
zzynxSoftware engineerCommented:
If I have understood Venabili well,
those files simply *are* created at every compile for every innerclass you have in your class.
(You can't avoid that. Why should you?)

>> will award you the points in a minute....
>> thank you ever so much!!
:°) Glad I could help.
0
VenabiliCommented:
>>those files simply *are* created at every compile for every innerclass you have in your class.

Exactly. Just need to make sure when you create a final version to make a clean rebuild so everything old to be deleted:)
If teh iner classes are anonimous - you have these numbers - applicationGUI$1 . Otherwise they are applicationGUI$MyClassName :). If you clean rebuild - next time you will receive teh same names. Otherwise you more likely to receive applicationGUI$2 and applicationGUI$MyClassName2 (depends on which file is changed and so on)

PS: It is not Netbeans that makes them. JBuilder does the same thing. I think any editor will do them

>>so have i to rebuild then recompile then run and this will stop the file being created from the inner class??

I do not remember how these were called in the NetBeans... But you do not need to care for them. Just make sure teh final version is clean one - deleting ANY class for example before the compilation will make the trick -- and will garuantee that you have no strange things there :) BUT you will always have 1 class for every Ineer class. The idea is not to have more than one for one Innerclass
>>if im creating small gui, i write the code my self, but this gui is to be the full size of the screen and i cant seem to get the layout working correct...

Well... I do it alone for every GUI. OR use the editor and then refactor... major refactoring :)

Good that you found your solution here:))

Venabili
0
NaeemgCommented:
Sorry, I'll care next time.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.