加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 是否可以在JFileChooser窗口中选择文件名?

发布时间:2020-12-15 02:17:02 所属栏目:Java 来源:网络整理
导读:我可以使用以下命令在JFileChooser窗口中设置默认文件名: fileChooser.setSelectedFile(); 我想知道是否也可以选择它,所以如果你想将文件另存为其他东西,你可以立即开始改写它.感谢您的帮助. package filetest;import java.awt.event.*;import java.io.File
我可以使用以下命令在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,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);
    }
}

解决方法

它默认在我输入的机器上执行此操作:

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:UsersubPicturesCapt.PNG"));
        int returnVal = chooser.showOpenDialog(null);
        if(returnVal == JFileChooser.APPROVE_OPTION)
           System.out.println("You chose to open this file: "+chooser.getSelectedFile().getName());
    }

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读