Rashad.Z
Rashad.Z

Reputation: 2604

How can I set the file name field in JFileChooser to the file the user wants to save?

I am using netbeans. I added a JFileChooser and want to use it to save files to specific location that the user wants. The user will choose from a JTable the file name that he wants to save and then the JFileChooser will open. The problem is that I want the "File Name" field in the JFileChooser to be set to the String name of the file the user wants to save. Is there a method in JFileChooser to do this?

JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
    File file = fileChooser.getSelectedFile();
    fileChooser.setSelectedFile(file);
}

Upvotes: 1

Views: 1358

Answers (1)

Patrick
Patrick

Reputation: 4562

try this...

package de.professional_webworkx.filechoosing;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;

public class MyFileChooser extends JFrame {

    private JFileChooser chooser;
    private JButton saveBtn;
    private MyFileChooser myFileChooser;
    public MyFileChooser() {

        myFileChooser = this;
        saveBtn = new JButton("Save");
        saveBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                chooser = new JFileChooser(System.getenv("user.home"));
                chooser.setSelectedFile(new File(<YOUR_STRING>));
                chooser.showSaveDialog(myFileChooser);
            }
        });
        this.getContentPane().add(saveBtn);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(640, 480);

        this.pack();
        this.setVisible(true);
    }

    public static void main(String[] args) {

        new MyFileChooser();
    }
}

Replace with the String, you get from the user out of your JTable.

Upvotes: 1

Related Questions