Right-click event in Java Swing

In this tutorial, you are going to learn the Java program to perform right-click event in Java Swing.

Perform Right-click event in Java Swing

In Java Swing, this event is performed using a mouse listener i.e. the ‘MouseAdapter’ class. This provides a default implementation for the ‘MouseListener’ and ‘MouseMotionListener’ interfaces. We are going to write a program where, when a right-click is given, it is going to ask to select an option.

Steps:

  1. Create the JFrame and JPanel for creating a main window and to detect the right-click respectively.
  2. Then create a Popup Menu so that a popup will appear with options when a right-click is detected.
  3. Add the Mouse Listener i.e. MouseAdapter to handle mouse events.

Mouse Listener: A Mouse Listener is used to handle the mouse events. In this two mwthods namely ‘mousePressed’ and ‘mouseReleased’ are used to check the event is a popup trigger or not. If this method returs true then a popup will appear.

Java program is as follows:

import javax.swing.*;
import java.awt.event.*;

public class CodeSpeedy {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
    private static void createAndShowGUI() {
        JFrame frame = new JFrame("Right-click event");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        frame.add(panel);
        JPopupMenu popupMenu = new JPopupMenu();
        JMenuItem menuItem1 = new JMenuItem("Hey");
        JMenuItem menuItem2 = new JMenuItem("Hello");
        popupMenu.add(menuItem1);
        popupMenu.add(menuItem2);
        panel.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    showPopup(e);
                }
            }
            public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    showPopup(e);
                }
            }
            private void showPopup(MouseEvent e) {
                popupMenu.show(e.getComponent(), e.getX(), e.getY());
            }
        });
        frame.setSize(400, 300);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

Output:

Right-click event window after running the program.

After a right click is given, it will detect the right-click and display the following options

Options that appear after a right-click is detected.

Leave a Reply

Your email address will not be published. Required fields are marked *