问题
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.
回答1:
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
final 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(j);
}
}
});
回答2:
The source of the Action event will be the JMenuItem that you clicked on so you can just use code like:
JMenuItem mi (JMenuItem)e.getSource();
menu.remove( mi );
Also, there is no need to create unique ActionListeners. You can create a shared listener with code like:
ActionListener removeItem = (new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JMenuItem mi = (JMenuItem)e.getSource();
int reply = JOptionPane.showConfirmDialog(null,
"Are you sure you want to delete racer " + mi.getText() + "?", "Delete?",
JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION)
{
r.delete();
racerDelete.remove(mi);
}
}
};
for (final Racer r : Racer.getAllRacers())
{
JMenuItem j = new JMenuItem(r.getName());
racerDelete.add(j);
j.addActionListener(removeItem);
}
来源:https://stackoverflow.com/questions/19326806/is-it-possible-to-remove-a-jmenuitem-from-a-jmenu-given-only-the-string-associat