I have a Java GUI project containing a JMenuBar and I just added a JToolBar. In the previous version, the events were implemented in the same class that extends the JMenuBar. I found it lame and moved the events in another class that extends AbstractAction. My aim is to centralize all the common events to make them react to different sources (JMenuBar, JToolBar etc.). But, I have a problem with the JFileChooser.showOpenDialog() method. This method takes as an argument the parent component for the dialog. If I do this :
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;
}
I get the following error :
The method showOpenDialog(component) in the type JFileChooser is not applicable for the arguments (ActionUsuels).
I guess this is normal because ActionUsuels doesn't extend any JComponent class. But how can I overpass that ? Is what I'm trying to do a bad practice ? My intention is to write the events once and be able to call them from any component.
Just to make you understand what I'm doing, I have this in the Menu class:
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]);
Every item is associated to the name of the action, an icon and the suitable event !
Any idea ?
Thanks !
Usually, the parent class passed to JDialogs is the main JFrame of the application. Among other things, this allows for the dialog to be centered over the app's window.
Hopefully your action class will have access to the main frame and can pass a reference to it. One way to achieve this might be to pass the main frame as an argument to the ActionUsuels
constructor.
Failing that, null
is also a valid parent specification. Given null
, the dialog is centered on the screen but generally works OK anyway.
Bonne chance! :)