1

在我的应用程序中,我使用 FileChooser 来选择文件。应将所选文件的名称返回给另一个类。如何在日食中做到这一点?

4

3 回答 3

3

actionPerformed 在某些事件(例如单击按钮)时由事件调度线程调用,并且永远不应直接调用它。如果您想要一个显示 FileChooser 并返回所选文件的方法,则声明另一个可由 eventHandler 以及其他任何地方调用的方法:

public void actionPerformed(ActionEvent e) {
    File myFile = selectFile();
    doSomethingWith(myFile);
}

public File selectFile() {
    int returnVal = fc.showDialog(FileChooserDemo2.this,
                                  "Attach");
    //Process the results.
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        return fc.getSelectedFile();
    } else {
        return null;
    }
}
于 2010-04-21T10:31:22.713 回答
0

在此处查看 FileChooserDemo 和 FileChooserDemo2 ,了解如何使用 FileChooser。

这是代码的相关摘录:

    public void actionPerformed(ActionEvent e) {
    //Set up the file chooser.
    if (fc == null) {
        fc = new JFileChooser();

    //Add a custom file filter and disable the default
    //(Accept All) file filter.
        fc.addChoosableFileFilter(new ImageFilter());
        fc.setAcceptAllFileFilterUsed(false);

    //Add custom icons for file types.
        fc.setFileView(new ImageFileView());

    //Add the preview pane.
        fc.setAccessory(new ImagePreview(fc));
    }

    //Show it.
    int returnVal = fc.showDialog(FileChooserDemo2.this,
                                  "Attach");

    //Process the results.
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        log.append("Attaching file: " + file.getName()
                   + "." + newline);
    } else {
        log.append("Attachment cancelled by user." + newline);
    }
    log.setCaretPosition(log.getDocument().getLength());

    //Reset the file chooser for the next time it's shown.
    fc.setSelectedFile(null);
}
于 2010-04-19T11:21:19.020 回答
0

假设“A”类包含显示文件选择器的代码,“B”类需要该值,以下将满足您的需求。

class A {
    private PropertyChangerSupport changer = new PropertyChangerSupport(this);
    private File selectedFile = null;

    public void addPropertyChangeListener(String property, PropertyChangeListener listener) {
        changer.addPropertyChangeListener(property, listener);
    }

    public void removePropertyChangeListener(String property, PropertyChangeListener listener) {
        changer.removePropertyChangeListener(property, listener);
    }

    public void actionPerformed(ActionEvent evt) {
        // Prompt the user for the file
        selectedFile = fc.getSelectedFile();
        changer.firePropertyChange(SELECTED_FILE_PROP, null, selectedFile);
    }
}

class B {
    public B(...) {
        // ...
        A a = ...
        a.addPropertyChangeListener(new PropertyChangeListener() {
            public void propertyChanged(PropertyChangeEvent evt) {
                if (evt.getPropertyName().equals(A.SELECTED_FILE_PROP)) {
                    File selectedFile = (File)evt.getNewValue();
                    // Do something with selectedFile
                }
            }});
    }
}
于 2010-04-20T21:11:15.953 回答