私のアプリケーションでは、FileChooserを使用してファイルを選択します。選択したファイルの名前を別のクラスに返す必要があります。Eclipseでこれを行う方法は?
2595 次
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
クラス「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 に答える
0
FileChooser の使用方法については、こちらのFileChooserDemo と FileChooserDemo2 をご覧ください。
関連するコードの抜粋を次に示します。
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 に答える