tags:

views:

169

answers:

2

I'm creating JPopUpMenu with following code:

JPopupMenu popup1 = new JPopupMenu();
JPopupMenu popup2 = new JPopupMenu();

JMenuItem freeze = new JMenuItem("freeze");
freeze.addActionListener(new FreezActionListener(this));

JMenuItem unfreeze = new JMenuItem("unfreeze");
unfreeze.addActionListener(new UnFreezActionListener(this));

JMenuItem sortU = new JMenuItem("sort");
JMenuItem sortD = new JMenuItem("sort");



popup1.add(freeze);
popup1.add(unfreeze);
popup1.add(sortU);

popup2.add(freeze);
popup2.add(unfreeze);
popup2.add(sortD);

After executing this code, popup2 menu works fine but popup1 has only sortU item. If I add menu items first to popup2 and then to popup1, then popup1 works fine and popup2 doesn't.

Is it normal behavior or did I miss something ?
I've searched about this but can't find anything

+3  A: 

A JMenuItem belongs to one, and only one, JPopupMenu (or any other menu). You cannot add a Swing component to more than one container; if you do, then the component will automatically be removed from the previous container. So when you add freeze and unfreeze to popup2, they are being automatically removed from popup1.

What you need to do to make this work properly is to create a total of six JMenuItems, three for each menu. The fact that two pairs of menu items do the same thing is only reflected in that the ActionListener does the same thing for each. So....

JPopupMenu popup1 = new JPopupMenu();
JPopupMenu popup2 = new JPopupMenu();

FreezActionListener freezer = new FreezActionListener(this);

JMenuItem freeze1 = new JMenuItem("freeze");
freeze1.addActionListener(freezer);
JMenuItem freeze2 = new JMenuItem("freeze");
freeze2.addActionListener(freezer);

UnFreezActionListener unfreezer = new UnFreezActionListener(this);

JMenuItem unfreeze1 = new JMenuItem("unfreeze");
unfreeze1.addActionListener(unfreezer);
JMenuItem unfreeze2 = new JMenuItem("unfreeze");
unfreeze2.addActionListener(unfreezer);

JMenuItem sortU = new JMenuItem("sort");
JMenuItem sortD = new JMenuItem("sort");



popup1.add(freeze1);
popup1.add(unfreeze1);
popup1.add(sortU);

popup2.add(freeze2);
popup2.add(unfreeze2);
popup2.add(sortD);
jprete
There is no need to create multiple listeners. Listeners, unlike components, can be shared.
camickr
That's what happens when I hastily copy and paste code...thanks for the comment. I will fix that.
jprete
A: 

Actually the better solution is to create Actions. Actions can be shared and added to multiple components (JMenuItems, JButtons etc). You can even enable/disable the Action which will enable/disable all the components at the same time.

You can read the section from the Swing tutorial on How to Use Actions for more information.

camickr