Eclipse actionPerformed能否返回值?
在我的应用程序中,我使用文件选择器来选择文件。所选文件的名称应返回给另一个类。如何在eclipse中做到这一点?了解FileChooserDemo和FileChooserDemo2如何使用FileChooser 以下是代码的相关摘录:Eclipse actionPerformed能否返回值?,eclipse,swing,return-value,jfilechooser,Eclipse,Swing,Return Value,Jfilechooser,在我的应用程序中,我使用文件选择器来选择文件。所选文件的名称应返回给另一个类。如何在eclipse中做到这一点?了解FileChooserDemo和FileChooserDemo2如何使用FileChooser 以下是代码的相关摘录: public void actionPerformed(ActionEvent e) { //Set up the file chooser. if (fc == null) { fc = new JFileChooser(
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);
}
假设类“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
}
}});
}
}
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;
}
}