I have a JMenu populated with JMenuItems from a database that have listeners, one of them being to delete the entry from the database if selected. When this happens that JMenuItem should disappear from the menus. Here's a short bit as an example
for (final Racer r : Racer.getAllRacers()) {
JMenuItem j = new JMenuItem(r.getName());
racerDelete.add(j);
j.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int reply = JOptionPane.showConfirmDialog(null,
"Are you sure you want to delete racer " + r.getName() + "?", "Delete?",
JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION){
r.delete();
racerDelete.remove(???);
}
}
});
}
So what can I put in place of the "???"? The fields of r are about all I have to identify the JMenuItem. I already tried racerDelete.remove(j) which doesnt work and I'm not sure why.
The source of the Action event will be the JMenuItem that you clicked on so you can just use code like:
Also, there is no need to create unique ActionListeners. You can create a shared listener with code like:
The trick is to read the error message, which probably says something like "variable j must be declared final to be used inside the anonymous class". Change your code to