How to create toggle switch with G4P
in
Contributed Library Questions
•
3 months ago
I have been asked once or twice how to create a toggle (on/off) button with G4P. Unfortunately the library does not have one out-of-the-box solution.
It is possible to use the GCheckbox and change the graphic used to simulate a toggle button and I will show how to do it here.
The first thing to do is create a tiled image with the pictures to use for the two states. An example is shown here.
The code below was created using the GUI Builder tool, the statement at line 15 changes the image from the default tick-box to our own image above.
The width of the GCheckbox must be at least 12 pixels wider than the displayed image (i.e. half the full image width) otherwise it will cause an exception.
gui.tab (header comments removed)
It is possible to use the GCheckbox and change the graphic used to simulate a toggle button and I will show how to do it here.
The first thing to do is create a tiled image with the pictures to use for the two states. An example is shown here.
The code below was created using the GUI Builder tool, the statement at line 15 changes the image from the default tick-box to our own image above.
The width of the GCheckbox must be at least 12 pixels wider than the displayed image (i.e. half the full image width) otherwise it will cause an exception.
- // Need G4P library
- import g4p_controls.*;
- public void setup() {
- size(480, 320, JAVA2D);
- createGUI();
- customGUI();
- }
- public void draw() {
- background(230);
- }
- // Use this method to add additional statements
- // to customise the GUI controls
- public void customGUI() {
- mySwitch.setIcon("switch.jpg", 2, null, null);
- }
gui.tab (header comments removed)
- public void switch_clicked(GCheckbox source, GEvent event) { //_CODE_:mySwitch:429373:
- println("checkbox1 - GCheckbox event occured " + System.currentTimeMillis()%10000000 );
- } //_CODE_:mySwitch:429373:
- // Create all the GUI controls.
- // autogenerated do not edit
- public void createGUI() {
- G4P.messagesEnabled(false);
- G4P.setGlobalColorScheme(GCScheme.BLUE_SCHEME);
- G4P.setCursor(ARROW);
- if (frame != null)
- frame.setTitle("Sketch Window");
- mySwitch = new GCheckbox(this, 110, 62, 30, 36);
- mySwitch.setOpaque(false);
- mySwitch.addEventHandler(this, "switch_clicked");
- }
- // Variable declarations
- // autogenerated do not edit
- GCheckbox mySwitch;