I'm having a problem using a JPopupMenu. I'm pretty sure it's something dumb I'm doing, as I'm new to using them, but it's got me stumped.
I create a MouseListener, in which I check for a right click. If I get one, I bring up the JPopupMenu, which has two menu items with associated listeners--each of which brings up a JDialog. It all works fine, except that each time I make a selection from the menu, it opens the JDialog multiple times. In essence, what it is doing is executing the menu item listener multiple times. The first time I click on a menu item it executes once. The second time it executes twice. The third time, three times...and so forth. It's almost like it's storing the earlier selections in a stack and re-executing them. Here's a sample of the relevant code
.
.
.
RightClickMenu rightClickMenu = new RightClickMenu();
.
.
.
class ListBoxMouseListener implements MouseListener {
publicvoid mouseClicked(MouseEvent e) {
if (e.getButton() == 3) { // i.e. if right-click
rightClickMenu.openRightClickMenu(e);
}
}
}
class RightClickMenu extends JPopupMenu {
publicvoid openRightClickMenu(MouseEvent event) {
this.add(menuItem1);
menuItem1.addActionListener(new MenuItem1Listener());
this.add(menuItem2);
menuItem1.addActionListener(new MenuItem2Listener());
}
}
class MenuItem1Listenerimplements ActionListener {
publicvoid actionPerformed(ActionEvent event) {
JDialog menuItem1Dialog = new JDialog();
}
}
class MenuItem2Listenerimplements ActionListener {
publicvoid actionPerformed(ActionEvent event) {
JDialog menuItem2Dialog = new JDialog();
}
}
By the way, I'm running Java 5.0 in a Windows 2000 environment. Any help would be greatly appreciated. This is driving me nuts.
Just to be clear, what happens when this runs is that, if I right click and select menuItem1, the menuItem1Dialog comes up. If I then close it and repeat the process, menuItem1Dialog comes up twice. I close both of them, repeat the process and it comes up three times.
Sorry for the second post, but I couldn't figure out how to edit the first after I'd posted it.
You don't hae to assign the menus everytime you call the PopupMenu.
You are wondering why you didn't get multiple menus items?
The answer is simple: menuItem1 was created only once. You can't add it multiple times. On every right click there was created a new Action-Listener. That's why you had multiple instances of it.
That was it. That was the problem. I'm a little embarrassed about this one--I should have realized it myself, but it was getting late and I was brain-dead from staring at it all day. Thanks for your help, Matthias. Now maybe I can get this thing released this morning.