Java – can I select a file name in the Jfilechooser window?

I can set the default file name in the Jfilechooser window using the following command:

fileChooser.setSelectedFile();

I want to know if you can also select it, so if you want to save the file as something else, you can start rewriting it immediately Thank you for your help

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,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,ex);
                } catch (InstantiationException ex) {
                    java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE,ex);
                } catch (illegalaccessexception ex) {
                    java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE,ex);
                } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                    java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE,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);
    }
}

Solution

It does this by default on the machine I entered:

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());
    }

}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>