Mouse Right Click Example Java


This Java code on Mouse Right Click Example explains how to handle the right clicks of mouse key.

Mouse Right Click Example
import java.awt.*;
import java.awt.event.*;
public class Demo extends Frame
{
  Button btn;
  public Demo()
  {
    setLayout(new FlowLayout());
    btn = new Button("OK");

    btn.addMouseListener(new MyListener());

    add(btn);
    setSize(300,300);
    setVisible(true);
  }
  
  public static void main(String args[])
  {
    new Demo();
  }
}
class MyListener  extends MouseAdapter
{
  public void mouseClicked (MouseEvent e) 
  {       			// write here your event handling code
    if (e.getModifiers() == MouseEvent.BUTTON3_MASK)
    {
      System.out.println("You right clicked on the button");
    }
  }
}


Mouse Right Click ExampleOutput screen on Mouse Right Click Example

Other way of event handling is:

if(e.isMetaDown())
{
System.out.println(“You right clicked on the button”);
}

The static constant modifier MouseEvent.BUTTON3_MASK or the method isMetaDown() of MouseEvent differentiates the right clicks.

btn.addMouseListener(new MyListener());

Instead of button btn, it can be any GUI component like Checkbox etc. Just register the MouseListener or MouseAdapter to a GUI component you would like.

We extended MouseAdapter to override only one method mouseClicked (MouseEvent e) and if MosueListener is implemented, it is required to override all the five methods.

Also learn the handling of double and triple clicks of mouse key.

Do you know how to do the following?

1. Frame Icon
2. Frame Position
3. Styles of drawing polygon
4. Centered Text with Underline
5. Drawing Cylinder, Cube, Circle
6. Smiley Face and Nested Panels

Leave a Comment

Your email address will not be published.