Hi, im having trouble getting an actionListener to work on a
JMenuItem.. this is the method..
public JMenuItem createMenuItem(JMenuItem item, String ItemName,
boolean isEnabled)
{
item = new JMenuItem(ItemName);
item.addActionListener(this); //Uneffective!
item.setEnabled(isEnabled);
return item;
}
then add it to the JMenu/PopupMenu..
private JMenuItem newItem;
...
...
fileMenu.add(createMenuItem(newItem,"New",true));
then the actionPerformed()
actionPerformed(ActionEvent ae)
{
if(ae.getSource() == newItem)
{
//action code
}
}
The MenuItem is created, the String is passed to the label as the
MenuItem's name and the enabled state is set, but the actionListener
is uneffective?
hiwa - 15 Jan 2004 12:44 GMT
> if(ae.getSource() == newItem)
> {
> //action code
> }
> }
Is it really newItem? Try using getText() on the event source.
And/or add ActionListener directly to the newItem.
Peter Votruba - 15 Jan 2004 16:27 GMT
> Hi, im having trouble getting an actionListener to work on a
> JMenuItem.. this is the method..
...
> The MenuItem is created, the String is passed to the label as the
> MenuItem's name and the enabled state is set, but the actionListener
> is uneffective?
newItem will always be "null", because createMenuItem will not change, and
therefore "(ae.getSource() == newItem)" will never evaluate to true.
Try this instead:
public JMenuItem createMenuItem(String ItemName, boolean isEnabled)
{
JMenuItem item = new JMenuItem(ItemName);
item.addActionListener(this); //Uneffective!
item.setEnabled(isEnabled);
return item;
}
...
private JMenuItem newItem1;
private JMenuItem newItem2;
...
...
newItem1 = createMenuItem("New",true);
fileMenu.add(newItem1);
newItem2 = createMenuItem("Exit",true);
fileMenu.add(newItem2);
...
... actionPerformed(ActionEvent ae)
{
if(ae.getSource() == newItem1) {
//action code
} else if(ae.getSource() == newItem2) {
//action code
}
}
But much better would be, to use Actions for each MenuItem.
HTH, Peter
Gregory A. Swarthout - 15 Jan 2004 17:48 GMT
> Hi, im having trouble getting an actionListener to work on a
> JMenuItem.. this is the method..
[quoted text clipped - 30 lines]
> MenuItem's name and the enabled state is set, but the actionListener
> is uneffective?
That's because you've added "new JMenuItem(ItemName)" to your menu,
not "newItem". You passed in a reference to "newItem" but the method
does not use that reference, it discards it in favor of a new
JMenuItem. This DOES NOT assign the new JMenuItem to "newItem".
Greg