Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: JFileChooser How to show Selected File in a textField

I have a JFileChooser and Im able to print the Absolute Path in console. I need to show the FilePath in a Text field as soon as the User selects the file.

Below is the code please let me know how to do it.

        public void actionPerformed(ActionEvent ae) {

        JFileChooser fileChooser = new JFileChooser();
        int showOpenDialog = fileChooser.showOpenDialog(frame);

        if (showOpenDialog != JFileChooser.APPROVE_OPTION) return;

Please let me know if you need any other details.

like image 434
Ananthavel Sundararajan Avatar asked Jan 01 '26 05:01

Ananthavel Sundararajan


1 Answers

You need to listen to the changes that occur when using the JFileChooser, see this snipet of code:

JFileChooser chooser = new JFileChooser();

// Add listener on chooser to detect changes to selected file
chooser.addPropertyChangeListener(new PropertyChangeListener() {
    public void propertyChange(PropertyChangeEvent evt) {
        if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY
                .equals(evt.getPropertyName())) {
            JFileChooser chooser = (JFileChooser)evt.getSource();
            File oldFile = (File)evt.getOldValue();
            File newFile = (File)evt.getNewValue();

            // The selected file should always be the same as newFile
            File curFile = chooser.getSelectedFile();
        } else if (JFileChooser.SELECTED_FILES_CHANGED_PROPERTY.equals(
                evt.getPropertyName())) {
            JFileChooser chooser = (JFileChooser)evt.getSource();
            File[] oldFiles = (File[])evt.getOldValue();
            File[] newFiles = (File[])evt.getNewValue();

            // Get list of selected files
            // The selected files should always be the same as newFiles
            File[] files = chooser.getSelectedFiles();
        }
    }
}) ;

All you need to do inside the first condition is set the value of your textfield to match the new selected filename. See this example:

yourTextfield.setText(chooser.getSelectedFile().getName());

Or just

yourTextfield.setText(curFile.getName());

It is the method getName() from class File that will give you what you need. Help your self from de API docs to see what each method does.

like image 125
javing Avatar answered Jan 02 '26 19:01

javing