Skip to content

Instantly share code, notes, and snippets.

@TechnicJelle
Last active February 22, 2024 20:51
Show Gist options
  • Save TechnicJelle/657f6de2e6d1938fd9a238d781e68911 to your computer and use it in GitHub Desktop.
Save TechnicJelle/657f6de2e6d1938fd9a238d781e68911 to your computer and use it in GitHub Desktop.
A simple class you can use to easily add dragging to your Processing window. Just click and drag anywhere inside the sketch, and it'll move the window along!
WindowDragger windowDragger;
void setup() {
size(400, 400);
//Set the start position of the window here (in screen pixels)
windowDragger = new WindowDragger(100, 100);
//OR:
//Pass in `this` in case you have a specific PApplet you want this WindowDragger to bind to.
//Set the start position of the window here (in screen pixels)
windowDragger = new WindowDragger(this, 100, 100);
}
void draw() {
background(0);
windowDragger.clickDragWindow();
}
//Necessary for getScreenMouse() to work:
import java.awt.Point;
import java.awt.MouseInfo;
class WindowDragger {
private PApplet pApplet;
private PVector winPos;
private PVector grabPoint = null;
//Set the start position of the window here (in screen pixels)
public WindowDragger(int x, int y) {
this.pApplet = null;
this.winPos = new PVector(x, y);
}
//Pass in `this` in case you have a specific PApplet you want this WindowDragger to bind to.
//Set the start position of the window here (in screen pixels)
public WindowDragger(PApplet pApplet, int x, int y) {
this.pApplet = pApplet;
this.winPos = new PVector(x, y);
}
public void clickDragWindow() {
if (pApplet == null ? mousePressed : pApplet.mousePressed) {
if (grabPoint == null) {
//Only set the grab point the first moment we click the window.
grabPoint = PVector.sub(getScreenMouse(), winPos);
}
moveToCursor();
} else {
grabPoint = null; //We don't have a grab point when we're not clicking the window
}
updateWindowPos();
}
private void updateWindowPos() {
if (pApplet == null) {
surface.setLocation(int(winPos.x), int(winPos.y));
} else {
pApplet.getSurface().setLocation(int(winPos.x), int(winPos.y));
}
}
private PVector getScreenMouse() {
Point p = MouseInfo.getPointerInfo().getLocation();
return new PVector(p.x, p.y);
}
private void moveToCursor() {
PVector sm = getScreenMouse();
if (grabPoint != null) sm.sub(grabPoint); //If we have a grab point, offset the window to that point
winPos.set(sm);
}
public PVector getWinPos() {
return winPos.copy();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment