Java: JFileChooser How to show the selected file in a text box

I have JFileChooser and Im able to print Absolute Path in the console. I need to show FilePath in a text box as soon as the user selects a file.

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

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.

+4
source share
3 answers

You need to listen to the changes that occur when using JFileChooser, see this snippet 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 that you need to do in the first condition sets the value of your text field in accordance with the newly selected file name. See this example:

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

Or simply

 yourTextfield.setText(curFile.getName()); 

This is the getName () method from the File class, which will give you what you need. Help yourself from the API docs to find out what each method does.

+4
source

This code can be used to display the path in the text box.

 if(fileChooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) { textField.setText(fileChooser.getSelectedFile().getAbsolutePath()); } 
+1
source

using what Genhis said, see the full block of code that you can use to get the browse button to put the file path in the correlating JTextField.

  JButton btnNewButton = new JButton("Browse"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { JFileChooser fc = new JFileChooser(); fc.setCurrentDirectory(new java.io.File("C:/Users")); fc.setDialogTitle("File Browser."); fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); if (fc.showOpenDialog(btnNewButton) == JFileChooser.APPROVE_OPTION){ textField.setText(fc.getSelectedFile().getAbsolutePath()); } } }); 
0
source

Source: https://habr.com/ru/post/1385306/


All Articles