使用JFileChooser保存

时间:2012-03-16 01:28:43

标签: java swing file save jfilechooser

我正在使用JFileChoosershowSaveDialoge()以及setSelectionMode(JfileChooser.DIRECTORIES_ONLY)来设置保存预选文件的位置以及将要调用的内容。

我希望用户能够选择新版本的名称以及放置它的位置。我该怎么做?我还想选择一个默认名称。

3 个答案:

答案 0 :(得分:13)

我希望以下代码符合您的问题要求。您的问题中的条件将在代码注释中得到解答。如果您需要澄清,请告诉我。

import java.awt.BorderLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class MyFileChooser extends JPanel implements ActionListener
{
    JButton saveButton;
    JTextArea content;
    JFileChooser jfc;

    private boolean docUpdate = false;
    private String default_filename = "default.txt";
    private String default_directory = "/home/foo/workspace";
    private int version = 0; 

    public MyFileChooser()
    {
        super(new BorderLayout());

        content = new JTextArea(5, 20);
        content.setMargin(new Insets(5, 5, 5, 5));
        content.getDocument().addDocumentListener(new DocumentListener()
        {

            @Override
            public void removeUpdate(DocumentEvent e)
            {
                System.out.println("remove update");
                docUpdate = true;               
            }

            @Override
            public void insertUpdate(DocumentEvent e)
            {
                System.out.println("insert update");
                docUpdate = true;
            }

            @Override
            public void changedUpdate(DocumentEvent e)
            {
                System.out.println("changed update");
                docUpdate = true;               
            }
        });
        JScrollPane logScrollPane = new JScrollPane(content);

        jfc = new JFileChooser();

        /**
         * Set a initial default directory and a initial default filename here. 
         */
        //fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        jfc.setCurrentDirectory(new File(default_directory));
        jfc.setSelectedFile(new File(default_filename));
        jfc.addPropertyChangeListener(new PropertyChangeListener() {

            @Override
            public void propertyChange(PropertyChangeEvent evt)
            {               
                if (docUpdate == true)
                {
                    /**
                     * User can use the suggested filename or remove the suggested,
                     * and enter a new filename.
                     * Here, we set to a new directory and of cause, user can select
                     * what is the directory he want.
                     */
                    jfc.setCurrentDirectory(new File("/home/foo"));
                    jfc.setSelectedFile(new File("default" + version + ".txt"));
                }               
            }
        });

        saveButton = new JButton("Save a File...");
        saveButton.addActionListener(this);

        JPanel buttonPanel = new JPanel(); 
        buttonPanel.add(saveButton);

        add(buttonPanel, BorderLayout.PAGE_START);
        add(logScrollPane, BorderLayout.CENTER);        
    }

    @Override
    public void actionPerformed(ActionEvent e)
    {

        int returnVal = jfc.showSaveDialog(MyFileChooser.this);
        if (returnVal == JFileChooser.APPROVE_OPTION)
        {
            File file = jfc.getSelectedFile();
            // save the file.
            BufferedWriter bw;
            try {
                bw = new BufferedWriter(new FileWriter(file));
                bw.write(content.getText());
                bw.flush();
            }               
            catch (IOException e1)
            {
                e1.printStackTrace();
            }
            version++;

        }
        else
        {
            System.out.println("Save command cancelled by user. ");
        }
        content.setCaretPosition(content.getDocument().getLength());

    }

    private static void createAndShowGUI()
    {       
        JFrame frame = new JFrame("FileChooserDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(new MyFileChooser());

        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {

            @Override
            public void run() 
            {
                createAndShowGUI();             
            }
        });
    }

}

答案 1 :(得分:1)

是的,这可以做到。显然,您需要使用属性更改侦听器在每次目录更改后设置默认文件名。您还需要确保使用showSaveDialog()并关闭仅限目录的选择模式(您希望它们在特定路径中选择文件名)

以下是有关属性更改侦听器部分的一些代码:

// create a new FileChooser
chooser = new JFileChooser();

String defaultFileName = "del.txt"

// add listener to filter changes
chooser.addPropertyChangeListener(JFileChooser.DIRECTORY_CHANGED_PROPERTY,
new PropertyChangeListener() {
    public void propertyChange(PropertyChangeEvent evt) {

        chooser.setSelectedFile(
            new File(chooser.getCurrentDirectory().getAbsolutePath() +
                "\\" + defaultFileName));


       chooser.updateUI();

   }
});

此代码来自此处的示例:http://www.codeguru.com/forum/archive/index.php/t-38894.html

答案 2 :(得分:1)

扩展Dialog并添加所需的组件,例如版本条目(JComboBox),默认文件名字段(JTextField),您可以在其中设置默认名称,按Ok,获取所有组件选定值,然后保存所需的组件。