G4P - Defining handleButtonEvents(..) in a Class

I’m coding native java classes using the Processing 3 IDE. Using G4P as my GUI library I’m trying to encapsulate one of my logical GUI components inside its own class, including the event handler for associated events. However, when I define a by-control-type event handler within this class G4P doesn’t see it and only appears to be looking for such event handlers within the main processing ‘implied’ class. Am I perhaps missing something as to how to have such event handlers defined within other classes of my program?

2 Likes

G4P allows you to specify the object and the class instance method to be used to handle events from a particular button. The following sketch demonstrates this

import g4p_controls.*;

Foo foo;

GButton btn;

void setup() {
  size(300, 300);
  fill(255);
  textSize(60);
  // Create object to handle events from the button
  foo = new Foo();
  btn = new GButton(this, 10, 10, 100, 40, "Click Me!");
  btn.addEventHandler(foo, "buttonClick");
}

void draw() {
  background(32);
  text(foo.clickCount(), 100, 150);
}

// Make this a top-level class
public static class Foo {
  private int clickCount = 0;

  public Foo() {
  }

  // Event handler for a G4P button
  public void buttonClick(GButton button, GEvent event) { 
    clickCount++;
  }

  public int clickCount() {
    return clickCount;
  }
}
2 Likes

Thank you for such a timely response, and on a weekend too. I see my mistake, I didn’t read the API close enough and simply assumed that the first argument to addEventHandler(…) needed to be a sketch like many of the others. But with your example and rereading the reference doc I see that it is actually meant to be the object containing the callback. This solves my issue, thank you. Also, thanks for contributing such a nice GUI library to the processing community, I’m finding it very useful.

2 Likes