mousePressed with multiple windows

I am working with processingpy and wanted to make a drawing program, I’ve created a basic color picker in one window, and then created a seperate one for drawing, but when I attempt to use mousePressed in the new window it only triggers when I click within the bounds of the color picker.

Welcome @stef0206

Because you’re using two windows, I assume you’ve structured your sketch using a class that extends PApplet (for the second window)? If so, this code might help, which includes a mousePressed() for both windows –

def setup():
    size(200, 200)
    window2 = Window2()
    switches = '--sketch-path=' + sketchPath(), ''
    PApplet.runSketch(switches, window2)
 
last_clicked_window = ''  # holds a 'red' or 'blue' string

# red window

def draw():
    background(255, 0, 0)
    text('last window you clicked:', 20, 20)
    text(last_clicked_window, 20, 40)

def mousePressed():
    global last_clicked_window
    last_clicked_window = 'red'

# blue window

class Window2(PApplet):
    def settings(w2):
        w2.size(200, 200)

    def draw(w2):
        w2.background(0, 0, 255)
        w2.text('last window you clicked:', 20, 20)
        w2.text(last_clicked_window, 20, 40)
    
    def mousePressed(self, w2):
        global last_clicked_window
        last_clicked_window = 'blue'
2 Likes

Thank you so much for posting this @tabreturn! I struggle with a second window from time to time and this helps enormously, I didn’t know how to handle the clicks!

I have fiddled with your example adding some ideas I learned from @GoToLoop I suppose:

last_clicked_window = ''  # holds a 'red' or 'blue' string

def setup():
    global window2
    size(200, 200)
    window2 = Window2('blue')  # now also runs & sets the title
    this.surface.setTitle('red') 
    print(dir(window2))
 
# red window

def draw():
    background(255, 0, 0)
    text('last window you clicked:', 20, 20)
    text(last_clicked_window, 20, 40)

def mousePressed():
    global last_clicked_window
    last_clicked_window = 'red'
    print(mouseX, mouseY)

# my window2 will sometimes stick around without this:    
def stop():   # undocumented hack, use exit() in Java mode
    window2.exit()
        
# blue window

class Window2(PApplet):
    def __init__(self, title=''):
        switches = '--sketch-path=' + sketchPath(), ''
        PApplet.runSketch(switches, self)
        self.surface.setTitle(title)
    
    def settings(self):
        self.size(200, 200)

    def draw(self):
        self.background(0, 0, 255)
        self.text('last window you clicked:', 20, 20)
        self.text(last_clicked_window, 20, 40)
      
    def mousePressed(self, mouse_event):
        global last_clicked_window
        last_clicked_window = 'blue'    
        print(self.mouseX, self.mouseY)
2 Likes