在JFileChooser窗口中选择文件名是否可能?

4

我可以使用以下代码在JFileChooser窗口中设置默认文件名:

fileChooser.setSelectedFile();

我想知道是否也可以选择文件名,这样如果您想将文件保存为其他名称,可以立即开始覆盖它。感谢任何有关此事的帮助。

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

你说的“select it”是什么意思? - Unai Vivi
1
在字段中突出显示文本,并使该字段获得焦点,这样当您开始输入时,现有文本将被替换。就像您在“文件名”字段中单击并按下Ctrl+A键的情况一样。 - Phil Whittaker
这对我来说是默认行为。我正在使用Windows 7上的JDK8。发布您的SSCCE以演示您的问题,以便其他人可以测试您的代码。 - camickr
3个回答

0

这是因为当您首次调用.setSelectedFile时,您的filepath为空字符串。

在向用户显示文件选择器后,设置filepath变量。

如果您在调用.showDialog之前将filepath的字符串值打印到控制台,您应该会看到这个值。


抱歉,我没有很清楚地解释我试图做什么。当文件首次打开时,filepath变量是一个空字符串。然后它包含已打开文件的名称,并用于在保存文件时填充“文件名”字段。如果您按Ctrl+O并选择文件,然后按Ctrl+S,应显示文件名。问题在于它没有被突出显示,而您的示例中的文件名是突出显示的。 - Phil Whittaker

0

这是我正在打字的机器的默认设置:

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

}

JDK8 x86_64 on Win - Unai Vivi
嗨,这对我也起作用,但我的版本(代码已添加上方)不起作用。 - Phil Whittaker

0
问题似乎是由这些行引起的:
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);
}

如果它们被移除,文件名会像Unai Vivi的示例一样突出显示。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接