Event Handling by Control Type
In this mechanism a single event handler for all controls of a particular type. Try the following sketch in Processing.
import g4p_controls.*;
GButton btn0;
void setup() {
size(300, 200);
btn0 = new GButton(this, 40, 20, 100, 30, "My Button");
}
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 a event handler method to process it.
If you look in the console window in Processing you will see the following message
You might want to add a method to handle GButton events syntax is public void handleButtonEvents(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 handleButtonEvents(GButton button, GEvent event) {
println(button.getText() + " " + millis());
}
Now every time you clicked the button you will see the button text and the time since the sketch started in milliseconds -
My Button 3588 My Button 4534 My Button 5301
If we have more than one button the same event handler is used for both so we need to test which button is clicked. This sketch has 2 buttons but behaves just like the previous sketch.
import g4p_controls.*;
GButton btn0, btn1;
void setup() {
size(300, 200);
btn0 = new GButton(this, 40, 20, 100, 30, "First Button");
btn1 = new GButton(this, 40, 60, 100, 30, "Second Button");
}
void draw() {
background(240);
}
public void handleButtonEvents(GButton button, GEvent event) {
if(button == btn0){
println("You have clicked on the first button");
}
if(button == btn1){
println("You have clicked on the second button");
}
println("The sketch has been running for " + millis() + " milliseconds");
}
If you have many buttons each having more complex / sophisticated actions then the code can become difficult to maintain, in that case you might want to handle events by control.