Using mouse button events while developing sketches in the Eclipse IDE

I have taken the info provided by @GoToLoop and the code from the old forum to produce a simple sketch that creates and displays a Java Swing popup menu in Processing 3.5.4 (i.e. latest version). As GoToLoop states this will only work with the default JAVA2D renderer.

Couple of things to point out -

  1. According to the Java documentation the adapter should catch and test both RELEASED and PRESSED events because the trigger is system dependent.
  2. Both Processing and AWT have a class called MouseEvent so we must state explicitly which class we are using.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public JPopupMenu menu = new JPopupMenu();
public Component win; 

void settings() {
  size(400, 400);
}

void setup() {
  // Get the visual component for this sketch
  win = (Component) getSurface().getNative();
  // Create and add a menu item
  JMenuItem item = new JMenuItem("Item Label 1");
  item.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
      System.out.println("Item 1");
    }
  }
  );
  menu.add(item);
  item = new JMenuItem("Item Label 2");
  item.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
      System.out.println("Item 2");
    }
  }
  );
  menu.add(item);
  win.addMouseListener(new MouseAdapter() {    
    // The popup trigger depends on the OS so should check 
    // both RELEASED and PRESSED
    public void mouseReleased(java.awt.event.MouseEvent evt) {
      if (evt.isPopupTrigger()) {
        menu.show(evt.getComponent(), evt.getX(), evt.getY());
      }
    }

    public void mousePressed(java.awt.event.MouseEvent evt) {
      if (evt.isPopupTrigger()) {
        menu.show(evt.getComponent(), evt.getX(), evt.getY());
      }
    }
  }
  );
}

void draw() {
  background(100, 100, 255);
}
2 Likes