ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button

Java Swing: Menus and Toolbars, Part 4
Pages: 1, 2

Events

JPopupMenu objects fire a PopupMenuEvent under two conditions: when the menu becomes visible or invisible, or is canceled without a menu item selection. The class contains the standard addPopupMenuListener( ) and removePopupMenuListener( ) methods for maintaining a list of PopupMenuEvent subscribers.



public void addPopupMenuListener(PopupMenuListener l)
public void removePopupMenuListener(PopupMenuListener l)

Add or remove a PopupMenuListener from the object's event queue.

The ability to be notified right before the pop-up menu becomes visible gives you the opportunity to tweak the state and contents of the menu based on the current state of your application, which can make your interface even more helpful and context-sensitive.

Note that when the pop-up menu is canceled, it also becomes invisible, so two events are potentially triggered. The cancelation event itself seems to be fired rarely in current implementations, though. If you need to know when the menu goes away, use the popupMenuWillBecomeInvisible handler.

Constructors

public JPopupMenu( )
public JPopupMenu(String title)

Create an empty pop-up menu. The second constructor accepts a String as the title of the pop-up menu.

Menu Items

public JMenuItem add(JMenuItem menuItem)
public Component add(Component c)
public JMenuItem add(Action a)

Add various elements to the pop-up menus. Objects extending either JMenuItem or JComponent can be added, but the latter functions best if it implements the MenuElement interface. If you specify an Action, its many properties are used to derive an appropriate JMenuItem, and its text is placed to the right of any image icon. The item retains its association with the action so that updates to the action (changes in name, icon, enabled state, etc.) are reflected by the item. The resulting JMenuItem is then returned, which you can use to alter its formatting.

public JMenuItem insert(Action a, int index)
public Component insert(Component component, int index)

Insert a specific menu item at a particular index. You can pass in a JComponent or an Action to these methods. If you use a JComponent, it's best if it implements the MenuElement interface. If you specify an Action, its various properties are used to derive an appropriate JMenuItem, and its text is placed to the right of any image icon. As usual, the item retains its association with the action. The resulting JMenuItem is then returned, which you can use to alter its formatting. All menu item indices that were previously at or after the specified position are incremented.

public void addSeparator( )

Add a separator to the pop-up menu. Typically, a separator consists of a single horizontal line drawn across the pop-up menu. Note that, like menu items, the separator counts as an index in the menu. The separator used is an instance of an inner class, not the regular JSeparator; it is always horizontal.

Display

public void show(Component invoker, int x, int y)

Paint the pop-up menu at the requested coordinates. The method takes a reference to the invoking component. It is functionally equivalent to the following calls: setInvoker( ), setLocation( ), and setVisible( ).

public void setPopupSize(int width, int height)

An alternate way to establish a preferred size for the pop up. (The other way is the popupSize property, which takes a Dimension.)

Miscellaneous

public int getComponentIndex(Component c)

Return the index associated with the component reference c. If there is no match to the component passed in, the method returns -1.

public static boolean getDefaultLightWeightEnabled

Return the default value for the lightWeightPopupEnabled property.

public boolean isPopupTrigger(MouseEvent e)

Since SDK 1.3, an alternate way to check whether a given mouse event should trigger a pop-up menu in the current L&F.

public static void setDefaultLightWeightPopupEnabled(boolean aFlag)

Set the default value of the lightWeightPopupEnabled property, which controls whether a lightweight or heavyweight component is used for the pop up.

public void setSelected(Component c)

Force the pop-up menu's model to select a particular menu item. This forces a property change event in the pop-up menu's single selection model.

public void updateUI( )

Force the default user interface manager to update itself, thus resetting the delegate to display a new PopupMenuUI.

Menu Element Interface

public void menuSelectionChanged(boolean isIncluded)
public MenuElement[ ] getSubElements( )
public Component getComponent( )
public void processMouseEvent(MouseEvent event, MenuElement path[ ],
    MenuSelectionManager manager)
public void processKeyEvent(KeyEvent event, MenuElement path[ ],
    MenuSelectionManager manager)

Implement the MenuElement interface, which is covered later in this chapter.

Using Pop-up Menus

Here is a program that demonstrates the use of the JPopupMenu class. The example is similar to the one that generated Figure 14-9, except that the pop up communicates events from the pop-up menu and from each of its menu items.

//  PopupMenuExample.java
//
import java.awt.*;
import java.awt.event.*;
 
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
 
public class PopupMenuExample extends JPanel {
 
    public JPopupMenu popup;
 
    public PopupMenuExample(  ) {
        popup = new JPopupMenu(  ); 
        ActionListener menuListener = new ActionListener(  ) {
            public void actionPerformed(ActionEvent event) {
                System.out.println("Popup menu item [" +
                                   event.getActionCommand(  ) + "] was pressed.");
            }
        };
        JMenuItem item;
        popup.add(item = new JMenuItem("Left", new ImageIcon("left.gif")));
        item.setHorizontalTextPosition(JMenuItem.RIGHT);
        item.addActionListener(menuListener);
        popup.add(item = new JMenuItem("Center", new ImageIcon("center.gif")));
        item.setHorizontalTextPosition(JMenuItem.RIGHT);
        item.addActionListener(menuListener);
        popup.add(item = new JMenuItem("Right", new ImageIcon("right.gif")));
        item.setHorizontalTextPosition(JMenuItem.RIGHT);
        item.addActionListener(menuListener);
        popup.add(item = new JMenuItem("Full", new ImageIcon("full.gif")));
        item.setHorizontalTextPosition(JMenuItem.RIGHT);
        item.addActionListener(menuListener);
        popup.addSeparator(  );
        popup.add(item = new JMenuItem("Settings . . ."));
        item.addActionListener(menuListener);
 
        popup.setLabel("Justification");
        popup.setBorder(new BevelBorder(BevelBorder.RAISED));
        popup.addPopupMenuListener(new PopupPrintListener(  ));
 
        addMouseListener(new MousePopupListener(  ));
    }
 
    // An inner class to check whether mouse events are the pop-up trigger
    class MousePopupListener extends MouseAdapter {
        public void mousePressed(MouseEvent e) { checkPopup(e); }
        public void mouseClicked(MouseEvent e) { checkPopup(e); }
        public void mouseReleased(MouseEvent e) { checkPopup(e); }
 
        private void checkPopup(MouseEvent e) {
            if (e.isPopupTrigger(  )) {
                popup.show(PopupMenuExample.this, e.getX(  ), e.getY(  ));
            }
        }
    }
 
    // An inner class to show when pop-up events occur
    class PopupPrintListener implements PopupMenuListener {
        public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
            System.out.println("Popup menu will be visible!");
        }
        public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
            System.out.println("Popup menu will be invisible!");
        }
        public void popupMenuCanceled(PopupMenuEvent e) {
            System.out.println("Popup menu is hidden!");
        }
    }
 
    public static void main(String s[ ]) {
        JFrame frame = new JFrame("Popup Menu Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(new PopupMenuExample(  ));
        frame.setSize(300, 300);
        frame.setVisible(true);
    }
}

The interesting parts of this program are the methods of MousePopupListener. These call a private method, checkPopup( ), to see if we've received an event that should raise the pop-up menu. If we get a valid trigger event, we show the pop up at the mouse location. This is an alternative to the approach of overriding processMouseEvent( ) that was demonstrated in "Displaying the Pop-up Menu."

The PopupMenuEvent Class

This is a simple event that tells listeners that the target pop-up menu is about to become visible or invisible, or that it has been canceled. Note that it doesn't tell which one has occurred. The object implementing PopupMenuListener will define three separate methods that can be called by a pop-up menu; each one indicates exactly what happened with the target pop-up menu object.

Constructor
public PopupMenuEvent(Object source)

The constructor takes a reference to the object that fired the event.

The PopupMenuListener Interface

The PopupMenuListener interface, which is the conduit for receiving the PopupMenuEvent objects, contains three methods. One method is called when the pop up is canceled, and the other two indicate that the pop up is about to show or hide itself. This interface must be implemented by any listener object that wishes to be notified of changes to the pop-up menu.

Methods
public abstract void popupMenuCanceled(PopupMenuEvent e)

Called when the target pop-up menu is canceled or removed from the screen. (This seems to be called rarely in practice.)

public abstract void popupMenuWillBecomeInvisible(PopupMenuEvent e)

Called when the pop-up menu is about to be removed from the screen.

public abstract void popupMenuWillBecomeVisible(PopupMenuEvent e)

Called when the pop-up menu is about show itself on the screen. This is an excellent opport

unity to update the contents of the menu (or their enabled states) based on current application conditions.

In the next installment, learn about the JMenu Class.


Return to ONJava.com.