我有一个JMenu,其中包含来自具有侦听器的数据库中的JMenuItems,其中一个是从数据库中删除该条目(如果已选中)。当发生这种情况时,JMenuItem应该从菜单中消失。这是一个简短的例子
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(???);
}
}
});
}
那么我可以用什么代替“???”? r的字段是我必须识别JMenuItem的全部内容。我已经尝试过racerDelete.remove(j),它不起作用,我不知道为什么。
答案 0 :(得分:1)
诀窍是阅读错误消息,这可能说“变量j必须被声明为最终才能在匿名类中使用”。将您的代码更改为
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);
}
}
});
答案 1 :(得分:1)
Action事件的来源将是您单击的JMenuItem,因此您可以使用以下代码:
JMenuItem mi (JMenuItem)e.getSource();
menu.remove( mi );
此外,无需创建唯一的ActionListener。您可以使用以下代码创建共享侦听器:
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);
}