簡體   English   中英

如何使JFileChooser在用戶所在的當前目錄中打開?

[英]How do I make JFileChooser open in the current directory the user is in?

我不想指定目錄。 我只希望它自動“知道”並在用戶正在使用的目錄中打開。我該怎么做?

基本上,你不能。 您需要告訴它。

當使用null currentDirectory (例如默認構造函數)構造時,它將使用FileSystemView#getDefaultDirectory

您可以為每個基本任務創建一個JFileChooser實例(一個用於保存,一個用於打開),並簡單地維護該實例,它將“記住”它正在使用的最后一個目錄,您仍然需要為其播種。雖然有一個起始目錄

另一個選擇是構造某種庫調用,該庫調用可以基於某個唯一鍵加載並保存用戶使用的最后一個目錄。 這意味着您可以簡單地做類似...

File toFile = MyAwesomeLibrary.getSaveFile(APPLICATION_DOCUMENT_SAVE_KEY);

它將加載提供的密鑰的最后一個已知目錄,並顯示使用該值配置的JFileChooser ,並且如果用戶取消了操作,則能夠返回所選的Filenull ……例如。

此示例在首次顯示時默認為user.dir 然后,它保留選擇器的實例以自動跟蹤最后的加載或保存位置,如MadProgrammer所建議的那樣。

在此處輸入圖片說明

在此處輸入圖片說明

在此處輸入圖片說明

在此處輸入圖片說明

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.io.*;

public class ChooserInCurrentDir {

    // the GUI as seen by the user (without frame)
    JPanel gui = new JPanel(new BorderLayout());
    JFileChooser fileChooser;
    private JTextArea output = new JTextArea(10, 40);

    ChooserInCurrentDir() {
        initComponents();
    }

    public final void initComponents() {
        gui.setBorder(new EmptyBorder(2, 3, 2, 3));

        String userDirLocation = System.getProperty("user.dir");
        File userDir = new File(userDirLocation);
        // default to user directory
        fileChooser = new JFileChooser(userDir);

        Action open = new AbstractAction("Open") {

            @Override
            public void actionPerformed(ActionEvent e) {
                int result = fileChooser.showOpenDialog(gui);
                if (result == JFileChooser.APPROVE_OPTION) {
                    try {
                        File f = fileChooser.getSelectedFile();
                        FileReader fr = new FileReader(f);
                        output.read(fr, f);
                        fr.close();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
        };

        Action save = new AbstractAction("Save") {

            @Override
            public void actionPerformed(ActionEvent e) {
                int result = fileChooser.showSaveDialog(gui);
                throw new UnsupportedOperationException("Not supported yet.");
            }
        };

        JToolBar tb = new JToolBar();
        gui.add(tb, BorderLayout.PAGE_START);
        tb.add(open);
        tb.add(save);

        output.setWrapStyleWord(true);
        output.setLineWrap(true);

        gui.add(new JScrollPane(
                output,
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
    }

    public final JComponent getGui() {
        return gui;
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                ChooserInCurrentDir cicd = new ChooserInCurrentDir();
                JFrame f = new JFrame("Chooser In Current Dir");
                f.add(cicd.getGui());
                // Ensures JVM closes after frame(s) closed and
                // all non-daemon threads are finished
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                // See http://stackoverflow.com/a/7143398/418556 for demo.
                f.setLocationByPlatform(true);

                // ensures the frame is the minimum size it needs to be
                // in order display the components within it
                f.pack();
                // should be done last, to avoid flickering, moving,
                // resizing artifacts.
                f.setVisible(true);
            }
        };
        // Swing GUIs should be created and updated on the EDT
        // http://docs.oracle.com/javase/tutorial/uiswing/concurrency
        SwingUtilities.invokeLater(r);
    }
}

如果要設置目錄,它們位於文件選擇器的上一個打開位置,則需要設置當前目錄。

//This will set the directory to the directory they previously chose a file from.
fileChooser.setCurrentDirectory(fileChooser.getCurrentDirectory());

我不確定這是否是您要查找的內容,但是當他們選擇一個文件然后去選擇另一個文件時,它將保留上一個選擇中的目錄。

如果希望您的應用程序查找用戶的工作目錄,則可以嘗試以下操作:

String curDir = System.getProperty("user.dir");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM