Event Handling by Control

In this mechanism each control has its own event handler. Try the following sketch in Processing.

import g4p_controls.*;

GButton btn0;

void setup() {
  size(300, 200);
  btn0 = new GButton(this, 40, 20, 100, 30, "First Button");
  btn0.addEventHandler(this, "handleBtn0");
}

void draw() {
  background(240);
}

If you run the sketch the button appearance changes as the mouse passes over the button and when the button is clicked, but the sketch does nothing with the event because we have not created the event handler method to process it.

If you look in the console window in Processing you will see the following message

The GButton class cannot find this method 
	public void handleBtn0(GButton button, GEvent event) { /* code */ }
			  

Simply copy and paste the last line into the sketch and add the code to be executed when the button is clicked like this

public void handleBtn0(GButton button, GEvent event) {
  println("You have clicked on the first button");
}

When you click on the button now you will see the message "You have clicked on the first button" appear in Processing's console pane.

The folowing sketch extends this example to include a second button.

import g4p_controls.*;

GButton btn0, btn1;

void setup() {
  size(300, 200);
  G4P.messagesEnabled(false);
  btn0 = new GButton(this, 40, 20, 100, 30, "First Button");
  btn0.addEventHandler(this, "handleBtn0");
  btn1 = new GButton(this, 40, 60, 100, 30, "First Button");
  btn1.addEventHandler(this, "handleBtn1");
}

void draw() {
  background(240);
}

public void handleBtn0(GButton button, GEvent event) {
  println("You have clicked on the first button");
}

public void handleBtn1(GButton button, GEvent event) {
  println("You have clicked on the second button");
}

If want the buttons to share the same event handler then simply modify the addEventHandler calls to point to the same method.

Of the two G4P event handling mechanisms this is the prefered option because it separates the program logic for each control. This makes the sketch code easier to maintain.