摇摆:处理JFileChooser结果后采取行动? [英] Swing: process JFileChooser result after action?
本文介绍了摇摆:处理JFileChooser结果后采取行动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想对JFileChooser按钮使用Abstract动作,因为会有很多这样的动作.
I want to use an Abstract action for JFileChooser buttons because there will be dozens of these.
public class OpenFileAction extends AbstractAction {
JFrame frame;
JFileChooser chooser;
OpenFileAction(JFrame frame, JFileChooser chooser) {
super("Open...");
this.chooser = chooser;
this.frame = frame;
}
public void actionPerformed(ActionEvent evt) {
// Show dialog; this method does not return until dialog is closed
chooser.showOpenDialog(frame);
}
};
很显然,我想将JFileChooser结果写入变量.操作完成后如何访问e.getSource()?这是行不通的,因为它是在FileChooser对话框打开之前触发的:
Obviously I want to write the JFileChooser result to a variable. How can I access e.getSource() AFTER the action is finished? This does not work because it is triggered before the FileChooser Dialog opens:
JButton btnNewButton_1 = new JButton(new OpenFileAction(new JFrame(), new JFileChooser(new File(".")) ) );
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//process e.getSource() ?
}
});
推荐答案
我认为您所追求的是以下几点:
I think what you're after is the following:
public abstract class OpenFileAction extends AbstractAction {
JFrame frame;
JFileChooser chooser;
public OpenFileAction(JFrame frame, JFileChooser chooser) {
super("Open...");
this.chooser = chooser;
this.frame = frame;
}
public void actionPerformed(ActionEvent evt) {
int option = chooser.showOpenDialog(this.frame);
if (option == JFileChooser.APPROVE_OPTION) {
File selectedFile = chooser.getSelectedFile();
doWithSelectedFile(selectedFile)
}
}
/**
* Method to override, which gets called with the selected file.
*/
protected abstract doWithSelectedFile(File file);
}
...
OpenFileAction action = new OpenFileAction(frame, new JFileChooser(new File("."))) {
@Override
protected void doWithSelectedFile(File file) {
// do what you want here
}
};
JButton button = new JButton(action);
这篇关于摇摆:处理JFileChooser结果后采取行动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文