Monday, August 8, 2011

Popup menu in Java

Popup menu

It is also known as context menu. It is typically triggered by the right mouse button. For system with only one mouse button, it is triggered by pressing and holding the primary mouse button.

Mouse Event

In Java, the MouseListener interface is used for capturing and handling the mouse event. The mousePressed() and the mouseReleased() methods must be implemented in order to trigger a popup menu.

To implement a full MouseListener, we must also implements the following method :
  public void mouseEntered(java.awt.event.MouseEvent e)
  public void mouseExited(java.awt.event.MouseEvent e)
  public void mouseClicked(java.awt.event.MouseEvent e)

Since we are not interested in the above events, we will implement the above with empty methods.

Adding popup menu

We will need to use these two classes.
A single popup menu may contain multpile menu items, the following method create a simple popup menu with 3 menu items.


Whenever a menu item is clicked, an action event is triggered. We need to implement an ActionListener in order to capture the action event. For the ActionListener interface, the only method that required to be implemented is actionPerformed.


The following program will create a panel with a text field inside it. Type anything into it.
Right click the text field, click "select all", click "copy", then click "paste" several times.

No comments:

Post a Comment