Can I select a file name in the JFileChooser window?

I can set the default file name: in the JFileChooser window using:

fileChooser.setSelectedFile();

I was wondering if you can also select it so that if you want to save the file as something else, you can immediately start redefining it. Thanks for any help on this.

package filetest;

import java.awt.event.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

@SuppressWarnings("serial")
class Editor {

    public static class TextClass extends JTextArea {

        FileClass fileClass = new FileClass();

        public void setKeyboardShortcuts() {
            fileClass.setKeyboardShortcuts();
        }

        private class FileClass {

            private File directory;
            private String filepath = "";
            private String filename = "";

            private void setKeyboardShortcuts() {

                Action ctrlo = new AbstractAction() {
                    public void actionPerformed(ActionEvent e) {
                        try {
                            openFile();
                        } catch (UnsupportedEncodingException e1) {
                        }
                    }
                };
                getInputMap().put(KeyStroke.getKeyStroke("ctrl O"), "ctrlo");
                getActionMap().put("ctrlo", ctrlo);

                Action ctrls = new AbstractAction() {
                    public void actionPerformed(ActionEvent e) {
                        try {
                            saveFile();
                        } catch (UnsupportedEncodingException e1) {
                        }
                    }
                };
                getInputMap().put(KeyStroke.getKeyStroke("ctrl S"), "ctrls");
                getActionMap().put("ctrls", ctrls);
            }

            private String selectFile(String fileaction) throws FileNotFoundException { 
                JFileChooser filechooser = new JFileChooser();
                if (directory != null) {
                    filechooser.setCurrentDirectory(directory);
                } else {
                    filechooser.setCurrentDirectory(new File("."));
                }
                filechooser.setSelectedFile(new File(filepath));
                int r = 0;
                if (fileaction.equals("openfile"))
                    r = filechooser.showDialog(new JPanel(), "Open file");
                else
                    r = filechooser.showDialog(new JPanel(), "Save file");
                if (r == JFileChooser.APPROVE_OPTION) {
                    try {
                        directory = filechooser.getSelectedFile().getParentFile();
                        filename = filechooser.getSelectedFile().getName();
                        return filename;
                    } catch (Exception exception) {
                        return "";
                    }
                } else {
                    return "";
                }
            }

            private void openFile() throws UnsupportedEncodingException {
                try {
                    String filestr = selectFile("openfile");
                    if (filestr.equals(""))
                        return;
                    else
                        filepath = filestr;
            } catch (FileNotFoundException ex) {
                    Logger.getLogger(Editor.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            private void saveFile() throws UnsupportedEncodingException {   
                try {
                    String filestr = selectFile("savefile");
                    if (filestr.equals(""))
                        return;
                    else
                        filepath = filestr;
                } catch (FileNotFoundException ex) {
                        Logger.getLogger(Editor.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                try {
                    for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                        if ("Nimbus".equals(info.getName())) {
                            javax.swing.UIManager.setLookAndFeel(info.getClassName());
                            break;
                        }
                    }
                } catch (ClassNotFoundException ex) {
                    java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
                } catch (InstantiationException ex) {
                    java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
                } catch (IllegalAccessException ex) {
                    java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
                } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                    java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
                }
                createAndShowGui();
            }
        });
    }

    private static void createAndShowGui() {

        JFrame frame = new JFrame();
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        JTextArea textArea = new TextClass();
        frame.add(textArea);
        ((TextClass) textArea).setKeyboardShortcuts();
        frame.setVisible(true);
    }
}
+4
source share
3 answers

It does this by default on the machine on which I type:

package stackoverflow;

import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 *
 * @author ub
 */
public class StackOverflow
{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        JFileChooser chooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Images", "jpg", "gif","png");
        chooser.setFileFilter(filter);
        chooser.setSelectedFile(new File("C:\\Users\\ub\\Pictures\\Capt.PNG"));
        int returnVal = chooser.showOpenDialog(null);
        if(returnVal == JFileChooser.APPROVE_OPTION)
           System.out.println("You chose to open this file: "+chooser.getSelectedFile().getName());
    }

}
0
source

This is because when you first call .setSelectedFile, yours filepathis an empty string.

You set your variable filepathafter the user shows the user the file.

filepath, .showDialog, .

0

The problem is apparently caused by these lines:

try {
    for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
            javax.swing.UIManager.setLookAndFeel(info.getClassName());
            break;
        }
    }
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}

If they are deleted, the file name is highlighted as in the Unai Vivi example.

0
source

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


All Articles