[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now

x
?
Solved

Require a simple save option

Posted on 2004-11-02
43
Medium Priority
?
757 Views
Last Modified: 2008-03-03
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
0
Comment
Question by:ellandrd
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 19
  • 17
  • 3
  • +2
43 Comments
 
LVL 37

Expert Comment

by:zzynx
ID: 12473956
>> 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
 
LVL 37

Expert Comment

by:zzynx
ID: 12473978
0
 
LVL 16

Author Comment

by:ellandrd
ID: 12474453
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 2

Expert Comment

by:shah1d1698
ID: 12475503
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
 
LVL 2

Expert Comment

by:shah1d1698
ID: 12475536
ooooooooooooo....zzynx has already posted it..... :-(
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12478457
>> 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
 
LVL 16

Author Comment

by:ellandrd
ID: 12483340
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
 
LVL 37

Expert Comment

by:zzynx
ID: 12483425
>> 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
 
LVL 16

Author Comment

by:ellandrd
ID: 12483500
well ive looked at them and i had no success

be right back with my code:

0
 
LVL 16

Author Comment

by:ellandrd
ID: 12483530
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
 
LVL 37

Expert Comment

by:zzynx
ID: 12483595
>> 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
 
LVL 16

Author Comment

by:ellandrd
ID: 12483710
ok this fixed the errors but when i select the save button, nothing happens??

any ideas why??

is my code correct??
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12483784
>> 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
 
LVL 16

Author Comment

by:ellandrd
ID: 12483928
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
 
LVL 16

Author Comment

by:ellandrd
ID: 12483985
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
 
LVL 37

Accepted Solution

by:
zzynx earned 2000 total points
ID: 12484047
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
 
LVL 16

Author Comment

by:ellandrd
ID: 12484073
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
 
LVL 16

Author Comment

by:ellandrd
ID: 12484136
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
 
LVL 37

Expert Comment

by:zzynx
ID: 12484187
>> 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
 
LVL 16

Author Comment

by:ellandrd
ID: 12484269
so is that why more files are being created and named as applicationGUI$1 to applicationGUI$15 everytime i compile it?
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12484272
Of course!
You nowhere initialized "fc", do you?

Replace

>> private JFileChooser fc;

by

 private JFileChooser fc = new JFileChooser();
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12484280
>> 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
 
LVL 16

Author Comment

by:ellandrd
ID: 12484292
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
 
LVL 37

Expert Comment

by:zzynx
ID: 12484314
>> i havnt add the layout manager code that i used in this class
Not needed, so far.
0
 
LVL 20

Expert Comment

by:Venabili
ID: 12484341
>> 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
 
LVL 16

Author Comment

by:ellandrd
ID: 12484367
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
 
LVL 37

Expert Comment

by:zzynx
ID: 12484386
So, for every compile a new file is added when there's an inner class in the code?
Mmm. Good to know Venabili.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12484402
What about

        private JFileChooser fc = new JFileChooser();

ellandrd?

0
 
LVL 16

Author Comment

by:ellandrd
ID: 12484457
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
 
LVL 16

Author Comment

by:ellandrd
ID: 12484495
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
 
LVL 16

Author Comment

by:ellandrd
ID: 12484507
can i just take out my layout class thats within the applicationGUI class and use it as a separate class instead??
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12484515
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
 
LVL 20

Expert Comment

by:Venabili
ID: 12484553
>> 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
 
LVL 16

Author Comment

by:ellandrd
ID: 12484641
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
 
LVL 37

Expert Comment

by:zzynx
ID: 12484701
My fault. That was a typo. Should be of course:

if (results == JFileChooser.CANCEL_OPTION )
0
 
LVL 16

Author Comment

by:ellandrd
ID: 12484730
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
 
LVL 37

Expert Comment

by:zzynx
ID: 12484761
>> i solved the problem if the user cancels the save option
Good!
Anything else?
0
 
LVL 16

Author Comment

by:ellandrd
ID: 12484778
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
 
LVL 16

Author Comment

by:ellandrd
ID: 12484794
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
 
LVL 37

Expert Comment

by:zzynx
ID: 12484918
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
 
LVL 20

Expert Comment

by:Venabili
ID: 12485110
>>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
 
LVL 5

Expert Comment

by:Naeemg
ID: 12490496
Sorry, I'll care next time.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses

656 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question