Maybe it’s a bad idea, but I wrote a subclass for JMenuItem to add a new constructor. Let’s call it JMenuItemX:
import java.awt.event.ActionListener;
import javax.swing.JMenuItem;
@SuppressWarnings("serial")
public class JMenuItemX extends JMenuItem
{
public JMenuItemX(final String the_text, final char the_mnemonic,
final ActionListener the_action)
{
super(the_text);
setMnemonic(the_mnemonic);
addActionListener(the_action);
}
}
Now, I am trying to add a tooltip to the component by using AbstractAction:
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JOptionPane;
@SuppressWarnings("serial")
public class AboutAction extends AbstractAction
{
public AboutAction()
{
super("About");
putValue(SHORT_DESCRIPTION, "Show the popup window");
}
@Override
public void actionPerformed(final ActionEvent the_event)
{
JOptionPane.showMessageDialog(null, "Hello World!");
}
}
and constructing the component as so (the JFrame, JMenuBar, and JMenu are already set up):
menu.add(new JMenuItemX("About", 'a', new AboutAction()));
(As you can see, if I am adding multiple menu items, this single-line format is easier to read.)
The menu item is visible with the correct text, and the mnemonic and action work as expected. But there is no tooltip… However, if I simply use JMenuItem, the tooltip works!
JMenuItem about = new JMenuItem(new AboutAction());
about.setMnemonic('a');
menu.add(about);
How can I get AbstractAction to work with my JMenuItem subclass?
Your overridden constructor doesn’t use the JMenuItem constructor taking an Action as argument, and doesn’t call
setAction()either. So your menu item is not associated to the action.I would not create a subclass just to add a constructor. Why not simply create a factory method?