我有一个包含JMenuBar的
Java GUI项目,我刚刚添加了一个JToolBar.在以前的版本中,事件是在扩展JMenuBar的同一个类中实现的.我发现它很蹩脚,并将事件移动到另一个扩展AbstractAction的类中.我的目标是集中所有常见事件,使他们对不同的来源做出反应(JMenuBar,JToolBar等).但是,我遇到了JFileChooser.showOpenDialog()方法的问题.此方法将对话框的父组件作为参数.
如果我这样做:
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import javax.swing.*;
import javax.swing.event.*;
public class ActionUsuels extends AbstractAction
{
private String nameAction;
/** Instance de MyFileChooser pour explorer les dossiers/fichiers*/
private MyFileChooser fc;
/** Instance d'OpenSave qui contient les algorithmes d'ouverture/sauvegarde*/
private OpenSave openSave;
ActionUsuels(String inName, String inPathIcon)
{
nameAction = inName;
putValue(Action.NAME, inName);
putValue(Action.SMALL_ICON, new ImageIcon(inPathIcon));
putValue(Action.SHORT_DESCRIPTION, inName);
this.fc = new MyFileChooser();
this.openSave = new OpenSave(Panneau.getUnivers());
}
public void actionPerformed(ActionEvent e)
{
// Evénement nouveau projet
if(nameAction == "OPEN_PROJECT")
{
fc.ContMode();
fc.refresh();
int returnVal = fc.showOpenDialog(ActionUsuels.this);
if (returnVal == MyFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
openSave.OpenCont(file);
}
}
static ActionUsuels actionInactive;
}
我收到以下错误:
The method showOpenDialog(component)
in the type JFileChooser is not
applicable for the arguments
(ActionUsuels).
我想这是正常的,因为ActionUsuels不扩展任何JComponent类.但我怎么能绕过那个呢?我正在努力做一个坏习惯吗?我的目的是编写一次事件,并能够从任何组件中调用它们.
只是为了让你明白我在做什么,我在菜单类中有这个:
actions = new ActionUsuels[nameActions.length];
for(int i = 0; i < nameActions.length; i++)
{
actions[i] = new ActionUsuels(nameActions[i], pathIcons[i]);
}
file_menu.add(actions[0]);
file_menu.addSeparator();
file_menu.add(actions[1]);
每个项目都与动作的名称,图标和合适的事件相关联!
任何的想法 ?
谢谢 !