Hi I am trying to write a file writer inside my mouse event code. I am trying to use the file name that comes from JTextField and write it into a file.

Here is my code:-

private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {                                      
               JFileChooser chooser = new JFileChooser();
               chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
               chooser.showSaveDialog(this);
               chooser.getSelectedFile();
               File selectedPfile = chooser.getSelectedFile();
               jTextField1.setText(selectedPfile.getAbsolutePath());
               String text = jTextField1.getText();
               
try {
   PrintWriter dataOut = new PrintWriter(new FileWriter("TEXT.txt"), true);

   dataOut.println(text);
   dataOut.close();
}
catch(IOException e) {}
               
    }

Thanks

Its not working. Simple.
This code is not writing the file.

Any suggestions are welcome.

Its not working. Simple.
This code is not writing the file.

Any suggestions are welcome.

Post complete source code.

I actually want to use the string in JTextField as a filename which will be saved after reading and writing without having to print and show on the Panel.

Thanks

I actually want to use the string in JTextField as a filename which will be saved after reading and writing without having to print and show on the Panel.

.....
String text = jTextField1.getText();
try {
   PrintWriter dataOut = new PrintWriter(new FileWriter(text), true);
....

Best not to do stuff like writing files on the Swing event thread because it interferes with the UI. When you get this working, wrap the code in a SwingWorker.

This article has been dead for over six months. Start a new discussion instead.