Duplicate :
|
The JPopup component never announces a "popupMenuCanceled" event. It is very important for the get an event if the popup menu is left without a selection. The singleSelectionModel doesn't keep the right state - even if I select a menuitem. The following source code demonstrates the problem (it is out of the book "programming with jfc") //Copyright 1998 John Wiley and Sons, Inc. import java.applet.*; import java.util.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; public class Popup extends JComponent implements ActionListener,PopupMenuListener,ChangeListener { JPopupMenu popup; JMenuItem mi1, mi2, mi3; public Popup() { popup = new JPopupMenu(); popup.setLightWeightPopupEnabled(false); mi1 = new JMenuItem("This"); mi1.addActionListener(this); mi1.setActionCommand("This"); popup.add(mi1); mi2 = new JMenuItem("That"); mi2.addActionListener(this); mi2.setActionCommand("That"); popup.add(mi2); mi3 = new JMenuItem("The Other"); mi3.addActionListener(this); mi3.setActionCommand("The Other"); popup.add(mi3); popup.addPopupMenuListener(this); popup.setOpaque(true); popup.setLightWeightPopupEnabled(true); addMouseListener(new PopupMouser(popup)); popup.getSelectionModel().addChangeListener(this); } public void paint(Graphics g) { Dimension size = getSize(); g.setColor(Color.darkGray); g.fillRect(0,0,size.width,size.height); } public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); System.out.println(command); } public void stateChanged(ChangeEvent e) { System.out.println ("State changed!"); } /* Popup Listener Methods*/ public void popupMenuWillBecomeVisible(PopupMenuEvent e) { System.out.println("Popup will become visible."); } public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { System.out.println("Popup will become invisible."); } public void popupMenuCanceled(PopupMenuEvent e) { System.out.println("Popup cancelled."); } public Dimension getPreferredSize() { return new Dimension(300, 300); } public static void main(String s[]) { JFrame frame = new JFrame("Popup Example"); Popup pup = new Popup(); frame.setForeground(Color.black); frame.setBackground(Color.lightGray); frame.addWindowListener(new WindowCloser()); frame.getContentPane().add(pup,"Center"); frame.setSize(pup.getPreferredSize()); frame.setVisible(true); } } class PopupMouser extends MouseAdapter { JPopupMenu popup; public PopupMouser(JPopupMenu p) { popup = p; } public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { popup.show(e.getComponent(), e.getX(), e.getY()); } } public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) { popup.show(e.getComponent(), e.getX(), e.getY()); } } } class WindowCloser extends WindowAdapter { public void windowClosing(WindowEvent e) { Window win = e.getWindow(); win.setVisible(false); System.exit(0); } }