Java:JFileChooser如何在textField中显示所选文件

时间:2011-12-08 09:07:01

标签: java swing jfilechooser

我有一个JFileChooser,我能够在控制台中打印绝对路径。 我需要在用户选择文件后立即在文本字段中显示FilePath。

以下是代码,请告诉我如何操作。

        public void actionPerformed(ActionEvent ae) {

        JFileChooser fileChooser = new JFileChooser();
        int showOpenDialog = fileChooser.showOpenDialog(frame);

        if (showOpenDialog != JFileChooser.APPROVE_OPTION) return;

如果您需要任何其他详细信息,请与我们联系。

3 个答案:

答案 0 :(得分:5)

您需要收听使用JFileChooser时发生的更改,请参阅此代码段:

JFileChooser chooser = new JFileChooser();

// Add listener on chooser to detect changes to selected file
chooser.addPropertyChangeListener(new PropertyChangeListener() {
    public void propertyChange(PropertyChangeEvent evt) {
        if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY
                .equals(evt.getPropertyName())) {
            JFileChooser chooser = (JFileChooser)evt.getSource();
            File oldFile = (File)evt.getOldValue();
            File newFile = (File)evt.getNewValue();

            // The selected file should always be the same as newFile
            File curFile = chooser.getSelectedFile();
        } else if (JFileChooser.SELECTED_FILES_CHANGED_PROPERTY.equals(
                evt.getPropertyName())) {
            JFileChooser chooser = (JFileChooser)evt.getSource();
            File[] oldFiles = (File[])evt.getOldValue();
            File[] newFiles = (File[])evt.getNewValue();

            // Get list of selected files
            // The selected files should always be the same as newFiles
            File[] files = chooser.getSelectedFiles();
        }
    }
}) ;

在第一个条件中你需要做的就是设置文本字段的值以匹配新选择的文件名。见这个例子:

yourTextfield.setText(chooser.getSelectedFile().getName());

或者只是

yourTextfield.setText(curFile.getName());

来自类File的getName()方法可以满足您的需求。 帮助你自己从de API docs看看每种方法的作用。

答案 1 :(得分:1)

您可以使用此代码在文本字段中显示路径。

if(fileChooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
    textField.setText(fileChooser.getSelectedFile().getAbsolutePath());
}

答案 2 :(得分:0)

使用Genhis所说的内容,请参阅完整的代码块,您可以使用它来浏览'浏览'按钮将文件路径放在相关的JTextField中。

        JButton btnNewButton = new JButton("Browse");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {             
            JFileChooser fc = new JFileChooser();
            fc.setCurrentDirectory(new java.io.File("C:/Users"));
            fc.setDialogTitle("File Browser.");
            fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            if (fc.showOpenDialog(btnNewButton) == JFileChooser.APPROVE_OPTION){
                textField.setText(fc.getSelectedFile().getAbsolutePath());
            }
        }
    });
相关问题