<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom">
	<channel>
      <title>Tagged with addbutton() - Processing 2.x and 3.x Forum</title>
      <link>https://forum.processing.org/two/discussions/tagged/feed.rss?Tag=addbutton%28%29</link>
      <pubDate>Sun, 08 Aug 2021 17:56:50 +0000</pubDate>
         <description>Tagged with addbutton() - Processing 2.x and 3.x Forum</description>
   <language>en-CA</language>
   <atom:link href="/two/discussions/taggedaddbutton%28%29/feed.rss" rel="self" type="application/rss+xml" />
   <item>
      <title>Found out too many { characters with a } to match it</title>
      <link>https://forum.processing.org/two/discussion/27813/found-out-too-many-characters-with-a-to-match-it</link>
      <pubDate>Sat, 21 Apr 2018 02:19:13 +0000</pubDate>
      <dc:creator>mromarcoder</dc:creator>
      <guid isPermaLink="false">27813@/two/discussions</guid>
      <description><![CDATA[<p>Im a processing user, and in one project im working in, my teacher ask me to start using tabs.But when i try to do so, when i draw all the figures it works with out errors, but im using buttons to change the colours of them in certain range,  with the help of "import controlP5.*;" an aleat appears when i run the project "Found out too many { characters with a } to match it", but as far as i know all the { do have a match }. So my question is why is this happening?</p>

<p>Main Tab</p>

<pre><code>yoshi yoshi;
Tree tree;
void setup() {
  size(900, 650);
  smooth();
  yoshi = new yoshi();
  tree= new Tree();
}
void draw() {
  background(255, 255, 255);
  yoshi.run();
  tree.run();
}
</code></pre>

<p>Yoshi tab</p>

<pre><code>class yoshi {

  import controlP5.*;
  PShape bot, bot1, bot2;
  PShape bot3, bot4, bot5;
  PShape bot6, bot7, bot8;
  PShape bot9, bot10, bot11;
  PShape bot12, bot13, bot14;
  PShape bot15, bot16;
  ControlP5 cp5;
  int c, c1, c2, c3, c4, c5;
  void yoshi() {
  }
  void run() {
    setup2();
  }
  void setup2() {
    bot=loadShape("cabezaverde.svg");
    bot1=loadShape("ojosblancos.svg"); 
    bot2=loadShape("ojosnegros.svg");
    bot3=loadShape("bocablanco.svg");
    bot4=loadShape("cuerpoblanco.svg");
    bot5=loadShape("cuerpoverde.svg");
    bot6=loadShape("espinasrojas.svg");
    bot7=loadShape("lineacaparazon.svg");
    bot8=loadShape("caparazonrojo.svg");
    bot9=loadShape("pieder.svg");
    bot10=loadShape("suelader.svg");
    bot11=loadShape("piernaizq.svg");
    bot12=loadShape("pieizq.svg");
    bot13=loadShape("suelaizq.svg");
    bot14=loadShape("brazoizq.svg");
    bot15=loadShape("brazoder.svg");
    cp5 = new ControlP5(this);

    cp5.addButton("figureA")
      .setValue(0)
        .setPosition(10, 10)
          .setSize(40, 19)
            ;
    cp5.addButton("figureB")
      .setValue(100)
        .setPosition(55, 10)
          .setSize(40, 19)
            ;
    cp5.addButton("figureC")
      .setPosition(100, 10)
        .setSize(40, 19)
          .setValue(0)
            ;
    cp5.addButton("figureD")
      .setValue(0)
        .setPosition(10, 35)
          .setSize(40, 19)
            ;
    cp5.addButton("figureE")
      .setValue(100)
        .setPosition(55, 35)
          .setSize(40, 19)
            ;
    display();
  }

  void display() {
    bot.disableStyle();
    bot1.disableStyle();
    bot2.disableStyle(); 
    bot3.disableStyle();
    bot4.disableStyle(); 
    bot5.disableStyle();
    bot6.disableStyle(); 
    bot7.disableStyle();
    bot8.disableStyle(); 
    bot9.disableStyle();
    bot10.disableStyle(); 
    bot11.disableStyle();
    bot12.disableStyle(); 
    bot13.disableStyle();
    bot14.disableStyle(); 
    bot15.disableStyle();
    stroke(0, 0, 0);
    strokeWeight(3);
    fill(c2);
    shape(bot, 404, 261, 100, 100);//cabeza-green
    fill(c4);
    shape(bot1, 424, 265, 100, 100);//ojos-white
    fill(c1);
    shape(bot2, 430, 268, 100, 100);//ojos-black
    fill(c4);
    shape(bot4, 436, 305, 100, 100);//cuerpo-white
    fill(c2);
    shape(bot5, 449, 303, 100, 100);//cuerpo-green
    fill(c3);
    shape(bot6, 452, 297, 100, 100);//espinas-red
    fill(c4);
    //shape(bot3, 20, -142, 100, 100);//boca-white
    shape(bot3, 468, 284, 100, 100);
    fill(c4);
    shape(bot7, 467, 314, 100, 100);//caparazon-white
    fill(c3);
    shape(bot8, 470, 312, 100, 100);//caparazon-red
    shape(bot9, 427, 336, 100, 100);//pieder-red
    fill(c5)
    shape(bot10, 427, 349, 100, 100);//suelader-golden
    fill(c2);
    shape(bot11, 457, 328, 100, 100);//piernaizq-green
    fill(c3);
    shape(bot12, 442, 340, 100, 100);//pieizq-red
    fill(c5)
    shape(bot13, 444, 354, 100, 100);//suelaizq-golden
    fill(c2);
    shape(bot14, 444, 311, 100, 100);//brazoizq-green
    shape(bot15, 428, 320, 100, 100);//brazoder-green
  }
  public void figureA(int value) {
    c1 = color(random(0, 27), random(0, 26), random(0, 26));//negro
  }
  public void figureB(int value) {
    c2 = color(random(21, 63), random(198, 208), random(4, 54));//verde
  }
  public void figureC(int value) {
    c3 =color(random(165, 255), random(0, 33), random(0, 33));//rojo
  }
  public void figureD(int value) {
    c4 = color(random(230, 255), random(215, 255), random(215, 255));//blanco
  }
  public void figureE(int value) {
    c5=color(random(203, 255), random(184, 222), random(0, 61));//dorado
  }
}
</code></pre>

<p>Tree tab</p>

<pre><code>class Tree {
  int xpos=0, ypos=0;
  int len;
  Tree() {
  }

  void run() {
    display();
  }
  void display() {
    // Start the tree from the bottom of the screen
    translate(width/2, height);
    stroke(0);
    branch(60);
    //translate(width/3, height);
    //stroke(0);
    //branch(60);
    noLoop();
  }

  void branch(float len) {
    strokeWeight(2);

    line(0, 0, 0, -len);
    // Move to the end of that line
    translate(0, -len);

    len *= 0.66;
    // All recursive functions must have an exit condition!!!!
    // Here, ours is when the length of the branch is 2 pixels or less
    if (len &gt; 2) {
      pushMatrix();    // Save the current state of transformation (i.e. where are we now)
      rotate(PI/5);   // Rotate by theta
      branch(len);       // Ok, now call myself to draw two new branches!!
      popMatrix();     // Whenever we get back here, we "pop" in order to restore the previous matrix state

      // Repeat the same thing, only branch off to the "left" this time!
      pushMatrix();
      rotate(-PI/5);
      branch(len);
      popMatrix();
    }
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Removing mouseover state in controlP5</title>
      <link>https://forum.processing.org/two/discussion/27703/removing-mouseover-state-in-controlp5</link>
      <pubDate>Fri, 06 Apr 2018 13:16:27 +0000</pubDate>
      <dc:creator>steve_j</dc:creator>
      <guid isPermaLink="false">27703@/two/discussions</guid>
      <description><![CDATA[<p>Having a small problem with controlP5 in android. The first press of a button triggers the mouseoverstate and not a trigger of the button. Is there anyway to bypass this? I have tried to set the mouseOver to true but doesnt help.</p>

<p>The three image files are being used for debug. Really i only need two.</p>

<pre><code>PImage[] imgsMinus = {loadImage("Volume-2.png"), loadImage("Volume-1.png"), loadImage("Volume.png")};
PImage[] imgsPlus = {loadImage("Volume-2.png"), loadImage("Volume-1.png"), loadImage("Volume.png")};

cp5.addButton("down")
      .setValue(-1)
      .setMouseOver(true)
      .setImages(imgsMinus)
      .updateSize()
      .setPosition(100, 100)

cp5.addButton("UP")
      .setValue(1)
      .setMouseOver(true)
      .setImages(imgsPlus)
      .updateSize()
      .setPosition(100, 100)
</code></pre>
]]></description>
   </item>
   <item>
      <title>How can I resize my sketch when using ControlP5 Buttons.</title>
      <link>https://forum.processing.org/two/discussion/26545/how-can-i-resize-my-sketch-when-using-controlp5-buttons</link>
      <pubDate>Tue, 27 Feb 2018 00:29:00 +0000</pubDate>
      <dc:creator>RogerL</dc:creator>
      <guid isPermaLink="false">26545@/two/discussions</guid>
      <description><![CDATA[<p>I'm very new to processing so please excuse my lack of proper terminology.  When I open this sketch and move my mouse over the buttons they highlight and work as expected.  When I make the screen much larger all appears ok except when I move my mouse over the buttons they no longer highlight and work unless I move my mouse to what appears to be the old unscaled location of the buttons.  Any Idea how to fix this?</p>

<p>Roger.</p>

<p>This is my code.  Hope I'm posting it right.</p>

<pre><code>import controlP5.*;
ControlP5 cp5;

PFont font1;

void setup() {

  size(500, 500);
  surface.setResizable(true);

  font1 = createFont("Ravie", 20, true);   

  cp5 = new ControlP5(this);
  cp5.addButton("button1")
    .setCaptionLabel("Button 1")
    .setPosition(100, 200)
    .setSize(125, 50)
    .setColorBackground(0)
    .setFont(font1)
    ;
  cp5.addButton("button2")
    .setCaptionLabel("Button2")
    .setPosition(100, 350)
    .setSize(125, 50)
    .setColorBackground(0)
    .setFont(font1)
    ;
}


void draw() {

  scale( width/500.0, height/500.0);

  background(0);
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>exit extended PApplet/ second window</title>
      <link>https://forum.processing.org/two/discussion/21813/exit-extended-papplet-second-window</link>
      <pubDate>Wed, 05 Apr 2017 00:28:53 +0000</pubDate>
      <dc:creator>jcunha</dc:creator>
      <guid isPermaLink="false">21813@/two/discussions</guid>
      <description><![CDATA[<p>I'm using processing 3.3. Basically this code opens a save window when "g" is pressed. You type the "name" and and "notes" and click on the save button so it appears on the main window. What I want is to be able to close the second window after clicking "save" and, if possible, when the second window opens i want it to open over the main window and not behind like it's doing. I've searched a lot and all the answers for this kind of problem don't work or the functions suggested are for preview versions of processing. Thank you for all the help</p>

<pre><code>import controlP5.*;
ControlP5 caixas;
String caixa1;
String caixa2;
String texto1;
String texto2;
Save cf;

void settings() {
  size(400,400,P3D);
}

void setup(){
}
void keyPressed() {
  if (key == 'g') {
  cf = new Save(this, 800, 800);
}
}

void draw() {
  background(0);
  text("texto 1: " + texto1 + "\ntexto 2: " + texto2,50,50);
}

class Save extends PApplet {

  int w, h;
  PApplet parent;
  ControlP5 cp5;

  public Save(PApplet _parent, int _w, int _h) {
    super();   
    parent = _parent;
    w=_w;
    h=_h;
    PApplet.runSketch(new String[]{this.getClass().getName()}, this);
  }

  public void settings() {
    size(w,h);
  }

  public void setup() {
  caixas = new ControlP5(this); 

  caixas.addTextfield("Name").setPosition(20, 100).setSize(200, 40);

  caixas.addButton("Save").setPosition(20,60).setSize(100,40);

  caixas.addTextfield("Notes").setPosition(20, 170).setSize(200, 40);

  }

  void draw() {
    background(40);
  }

  public void controlEvent(ControlEvent theEvent) {
    texto1 = caixas.get(Textfield.class,"Nome").getText();
    texto2 = caixas.get(Textfield.class,"Notas").getText();
// HERE THE FUNCTION OR ANYTHING TO MAKE IT CLOSE
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Trying to add CP5 buttons using Mouse events with UDP network communication</title>
      <link>https://forum.processing.org/two/discussion/26147/trying-to-add-cp5-buttons-using-mouse-events-with-udp-network-communication</link>
      <pubDate>Sun, 28 Jan 2018 01:51:02 +0000</pubDate>
      <dc:creator>Ragooman</dc:creator>
      <guid isPermaLink="false">26147@/two/discussions</guid>
      <description><![CDATA[<p>I'm still learning how to make GUI screens and this is my first attempt to add buttons together with mouse events. I've mostly used a command line style interfaces in the past over the serial port or network. This time I wanted to have a button send the command line in text over the network. So I started using the CP5 library and the mouse events function. But when I try this, something appears to be out of sync. This is a project using the RPI as an instrument to collect data.</p>

<p>But when I add the additional CP5 library and the mouse event function, in 'udp_server5', the packet messages are received out of sync. I don't get the correct packet when I click on any of the buttons. They seem to be out of sync by one or two messages. I would get the correct packet after a couple of mouse clicks. I use the console to print debug messages so I can follow the state of the program. I added some screenshots below to show what happens. The 'udp_server5' code is also show below.</p>

<p>I use the same python code on the RPI for either udp server code on the PC. I already worked out the udp network communications with my RPI with the previous code show below in 'udp_server4'. There, I just use a command line to send a text command over the network. My RPI is running python to decode the command, then acknowledge the command back to the server, along with a packet sequence# so I can know if I'm getting the correct packet. At the moment, I only decode 3 commands.</p>

<p>In the udp_server5 code, I use a button flag to keep track of which button I click on. From looking at the debug messages in the console, I see the button events occur last. I was expecting them to occur first when I click on any button. So the button flag doesn't get updated with the current value. And so the wrong command is sent over the network. When I click on the same button again, the button flag is finally updated with the correct value, so then the right command is sent over the network.</p>

<p>Another item I don't understand from looking at the debug messages. When I start the program I see Control Events already in my console from the 3 buttons I created without clicking on anything. so this also causes my Button Flag to begin with the wrong value.</p>

<p>I'm currently using Processing ver3.3.6. And I used the CP5 library examples from Processing to add the buttons to my code in 'udp server 5'. And I found the mouse event function on the reference page and in the examples. But I'm not sure if these steps are combined in the correct order.</p>

<p>Could I be using the wrong coding technique ?</p>

<p><strong>Here's the code for 'udp_server4'</strong></p>

<pre><code>//=====================================================
//UDP Server 4
//press any key to send a command message from the Server to RPI client
//The RPI client will reply back to the Server
//Send:    Server PC  (10.0.0.3)  to RPI Client(10.0.0.10)
//Receive: RPI Client (10.0.0.10) to Server PC (10.0.0.3)
//ControlP5 Library Buttons
//-----------------------------------------------------------------------------------
// import UDP library
import hypermedia.net.*;
// import Button library
//import controlP5.*;
//
UDP udp;  //define the UDP object
//ControlP5 cp5;
//
//-----------------------------------------------------------------------------------
//
int myColor = color(255);
int c1,c2;
int c = 0;
int indent = 25;
int ButtonFlag;
float n,n1;
//
String message1 = "";
String message2 = "00000";
String status = "";
char command;
//
//--------------------------------------------------------------------------------
void setup() 
{
  //create a new datagram connection
  //From Client to Server=5555
  //From Server to Client=5556
  //
  int UDP_port_rcv = 5555;
  int UDP_port_snd = 5556;
  //
  smooth();
  size(800, 600);
  background(128);
  //
  fill(255);  // Set fill to white
  noStroke();
  rect(350, 550, 55, 25, 5);
  //
  text("UDP SERVER 4\nEnter Command for client. ", indent, 40);
  //
  println("============================");
  println("UDP SERVER 4: ");
  //noStroke();
  //
  //--------------------------------------------------------------------------------
  // load a new font. ControlFont is a wrapper for processing's PFont
  PFont pfont = createFont("Courier",20,true); // use true/false for smooth/no-smooth
  //ControlFont font = new ControlFont(pfont,20); //font size for Text Field
  //
  //-----------------------------------
  udp = new UDP( this, UDP_port_rcv );  
  //
  //printout the connection activity
  //udp.log( true );
  //
  // wait for incoming message
  udp.listen( true );           
}

//--------------------------------------------------------------------------------
//process events
//keep draw() here to continue looping
void draw()
{
  //background(128);
  //clear text area for packet message
  fill(125);  // Set fill to gray
  stroke(1);
  rect(25,475,300,90);
  //
  //clear area for packet sequence#
  fill(255);  // Set fill to white
  noStroke();
  rect(350, 550, 55, 25, 5);
  //
  //display packet message
  fill(0);  // Set fill to black
  text("CMD: " + command,indent,500);
  text("RCVD: " + message1,indent,525);
  text("STATUS: " + status,indent,550);
  //
  //display packet sequence#
  fill(0);  // Set fill to black
  text(message2, 360, 550, 55, 55);
  //
}

//--------------------------------------------------------------------------------
//On key pressed event:
//send the command to the client
void keyPressed() 
{
  String ip       = "10.0.0.10"; // the Client IP address
  int port_snd    = 5556;        // Sent Port
  String commandS;
  switch (key) 
  {
    case 'c':
      command = key;
      status = "GOOD";
      //
      commandS = str(command);
      udp.send(commandS, ip, port_snd );   // the message to send
      println("&gt;&gt;&gt;Key Command Sent");
      break;
    case 'x':
      command = key;
      status = "GOOD";
      //
      commandS = str(command);
      udp.send(commandS, ip, port_snd );   // the message to send
      println("&gt;&gt;&gt;Key Command Sent");
      break;
    case 'z':
      command = key;
      status = "GOOD";
      //
      commandS = str(command);
      udp.send(commandS, ip, port_snd );   // the message to send
      println("&gt;&gt;&gt;Key Command Sent");
      break;
    default:
      command = key;
      message1 = "";
      status = "KEY COMMAND INCORRECT";
      println("***Incorrect Key Command***");
  }
}

//--------------------------------------------------------------------------------
//Extended handler
//In the Extended Handker,
//The two arguments representing in order, 
//the sender IP address and the sender port
public void receive( byte[] data, String ip, int port ) 
{
  // get the "real" message =
  // forget the ";\n" at the end &lt;-- !!! only for a communication with Pd !!!
  //data = subset(data, 0, data.length-2);

  //String message = new String( data );
  message1 = new String(data);
  //Extract Packet Sequence#
  message2 = new String(message1.substring(35,message1.length()));

  //print the result
  println( "RCVD: "+ip+":"+port+" = "+""+message1);
  //print packet sequence#
  println( "RCVD: "+message2);
  //
}

//=============================================================
</code></pre>

<p><strong>Here's the code for 'udp_server5'</strong></p>

<pre><code>//=====================================================
//UDP Server 5
//click mouse to send a command message from the Server to RPI client
//Send:    Server PC  (10.0.0.3)  to RPI Client(10.0.0.10)
//Receive: RPI Client (10.0.0.10) to Server PC (10.0.0.3)
//ControlP5 Library Buttons
//-----------------------------------------------------------------------------------
// import UDP library
import hypermedia.net.*;
// import Button library
import controlP5.*;
//
UDP udp;  //define the UDP object
ControlP5 cp5;
//
//-----------------------------------------------------------------------------------
//
int myColor = color(255);
int c1,c2;
int c = 0;
int indent = 25;
int ButtonFlag;
float n,n1;
//
String message1 = "";
String message2 = "00000";
String status = "";
char command = ' ';
//
String ip       = "10.0.0.10"; // the Client IP address
int port_snd    = 5556;        // Sent Port
byte[] data;
//
//--------------------------------------------------------------------------------
void setup() 
{
  //create a new datagram connection
  //From Client to Server=5555
  //From Server to Client=5556
  //
  int UDP_port_rcv = 5555;
  int UDP_port_snd = 5556;
  //
  smooth();
  size(800, 600);
  background(128);
  //
  fill(255);  // Set fill to white
  rect(350, 550, 55, 25, 5);
  //
  text("UDP SERVER 5\nEnter Command for client. ", indent, 40);
  //
  println("============================");
  println("UDP SERVER 5: ");
  //noStroke();
  //
  //--------------------------------------------------------------------------------
  // load a new font. ControlFont is a wrapper for processing's PFont
  PFont pfont = createFont("Courier",20,true); // use true/false for smooth/no-smooth
  ControlFont font = new ControlFont(pfont,20); //font size for Text Field
  //
  cp5 = new ControlP5(this);
  cp5.enableShortcuts();
  frameRate(50);
  //
  // create a new button 
  cp5.addButton("RESET")
     .setValue(0)
     .setPosition(100,100)
     .setSize(100,39)
     .setId(2);
     ;
  // create a new button 
  cp5.addButton("OHM")
     .setValue(100)
     .setPosition(100,140)
     .setSize(100,39)
     .setId(2);
     ;
  // create a new button 
  cp5.addButton("VOLTS")
     .setPosition(100,180)
     .setSize(100,39)
     .setValue(0)
     .setId(2);
     ;
  //--------------------------------------------------------------------------------
  // change the font and content of the captionlabels 
  // for both buttons create earlier.
  cp5.getController("RESET")
     .getCaptionLabel()
     .setFont(font)
     .toUpperCase(false)
     .setSize(16)
     ;
  //   
  cp5.getController("OHM")
     .getCaptionLabel()
     .setFont(font)
     .toUpperCase(false)
     .setSize(16)
     ;
  //   
  cp5.getController("VOLTS")
     .getCaptionLabel()
     .setFont(font)
     .toUpperCase(false)
     .setSize(16)
     ;
  //-----------------------------------
  udp = new UDP( this, UDP_port_rcv );  
  //
  //printout the connection activity
  //udp.log( true );
  //
  // and wait for incoming message
  udp.listen( true );           
}

//--------------------------------------------------------------------------------
//process events
// keep draw() here to continue looping
void draw()
{
  //background(128);
  //clear text area for packet message
  fill(125);  // Set fill to gray
  stroke(1);
  rect(25,475,300,90);
  //
  //clear number area for packet sequence#
  fill(255);  // Set fill to white
  noStroke();
  rect(350, 550, 55, 25, 5);
  //
  //display packet message
  fill(0);  // Set fill to black
  text("CMD: " + command,indent,500);
  text("RCVD: " + message1,indent,525);
  text("STATUS: " + status,indent,550);
  //
  //display packet sequence#
  fill(0);  // Set fill to black
  text(message2, 360, 550, 55, 55);
  //
}

//--------------------------------------------------------------------------------
//On key pressed event:
//send the command to the client

void keyPressed() 
{
  String ip       = "10.0.0.10"; // the Client IP address
  int port_snd    = 5556;        // Sent Port
  String commandS;
  println("------------------------------------------");
  switch (key) 
  {
    case 'c':
      command = key;
      status = "GOOD";
      //
      commandS = str(command);
      udp.send(commandS, ip, port_snd );   // the message to send
      println("&gt;&gt;&gt;Key Command Sent");
      break;
    case 'x':
      command = key;
      status = "GOOD";
      //
      commandS = str(command);
      udp.send(commandS, ip, port_snd );   // the message to send
      println("&gt;&gt;&gt;Key Command Sent");
      break;
    case 'z':
      command = key;
      status = "GOOD";
      //
      commandS = str(command);
      udp.send(commandS, ip, port_snd );   // the message to send
      println("&gt;&gt;&gt;Key Command Sent");
      break;
    default:
      command = key;
      message1 = "";
      status = "KEY COMMAND INCORRECT";
      println("***Incorrect Key Command***");
  }
}

//-----------------------------------------------------------------------

void mousePressed()
{
  println("------------------------------------------");
  switch (ButtonFlag)
  {
    case 1:
      command = 'c';
      status = "GOOD RESET COMMAND";
      println("Switch: Button Flag  from RESET: "+ButtonFlag);
      break;
    case 2:
      command = 'z';
      message1 = "";
      status = "GOOD OHM COMMAND";
      println("Switch: Button Flag  from OHM: "+ButtonFlag);
      break;
    case 3:
      command = 'x';
      message1 = "";
      status = "GOOD VOLTS COMMAND";
      println("Switch: Button Flag  from VOLTS: "+ButtonFlag);
      break;
  }  
  sendcmd();
}

//--------------------------------------------------------------------------------
//Transmit Command
public void sendcmd() 
{
  //String ip       = "10.0.0.10"; // the Client IP address
  //int port_snd    = 5556;        // Sent Port
  //
  println("------------------------------------------");
  String commandS = str(command);
      udp.send(commandS, ip, port_snd );   // the message to send
      println("&gt;&gt;&gt;Command Sent");
}

//--------------------------------------------------------------------------------
// Extended handler
//In the Extended Handker,
//The two arguments representing in order, 
//the sender IP address and the sender port
public void receive( byte[] data, String ip, int port ) 
{
  //String message = new String( data );
  println("------------------------------------------");
  message1 = new String(data);
  message2 = new String(message1.substring(35,message1.length()));

  //print the result
  //println( "receive: \""+message+"\" from "+ip+" on port "+port );
  println( "RCVD: "+ip+":"+port+" = "+""+message1);
  println( "RCVD: "+message2);
  //
}
//-----------------------------------------------------------------------
public void controlEvent(ControlEvent theEvent) {
  println("------------------------------------------");
  println("ControlEvent: ",theEvent.getController().getName());
  n = 0;
}

//-----------------------------------------------------------------------
// function RESET will receive changes from 
// controller with name COLORA
public void RESET(int theValue) {
  println("------------------------------------------");
  println("Button Event from RESET: "+theValue);
  ButtonFlag = 1;
  println("Button Flag  from RESET: "+ButtonFlag);
}

//-----------------------------------------------------------------------
// function OHM will receive changes from 
// controller with name COLORB
public void OHM(int theValue) {
  println("------------------------------------------");
  println("Button Event from OHM: "+theValue);
  ButtonFlag = 2;
  println("Button Flag  from OHM: "+ButtonFlag);
}

//-----------------------------------------------------------------------
// function VOLTS will receive changes from 
// controller with name COLORC
public void VOLTS(int theValue) {
  println("------------------------------------------");
  println("Button Event from VOLTS: "+theValue);
  ButtonFlag = 3;
  println("Button Flag  from VOLTS: "+ButtonFlag);
}

//====================================================
</code></pre>

<p><strong>Here's a screenshot from the console in when starting 'udp_server5'</strong>
<img src="https://forum.processing.org/two/uploads/imageupload/771/DXHPV3YV8NQG.jpg" alt="console_udpserver5-1" title="console_udpserver5-1" /></p>

<p><strong>Here's a screenshot from the console when I click on the RESET button in 'udp_server5'</strong>
<img src="https://forum.processing.org/two/uploads/imageupload/530/5OTCPU1WWRNP.jpg" alt="console_udpserver5-2" title="console_udpserver5-2" /></p>

<p><strong>Here's a screenshot from the gui screen when I click on the RESET button in 'udp_server5'</strong>
<img src="https://forum.processing.org/two/uploads/imageupload/721/TFXBEDZ5OQR7.jpg" alt="gui_udpserver5-1" title="gui_udpserver5-1" /></p>
]]></description>
   </item>
   <item>
      <title>PDF Export (Pattern Maker)</title>
      <link>https://forum.processing.org/two/discussion/25893/pdf-export-pattern-maker</link>
      <pubDate>Wed, 10 Jan 2018 03:01:32 +0000</pubDate>
      <dc:creator>digitalcoleman</dc:creator>
      <guid isPermaLink="false">25893@/two/discussions</guid>
      <description><![CDATA[<p>Hello all!</p>

<p>I have been making an app for my students called Pattern maker (<a rel="nofollow" href="https://github.com/digitalcoleman/generativeExamples/tree/master/patternMaker_v2">https://github.com/digitalcoleman/generativeExamples/tree/master/patternMaker_v2</a>)
which includes the ability to drag and drop svg files, create patterns with them, and export a pdf which we will later translate for a plotter.</p>

<p>The problem is that the more complex the svg file, the less likely that a pdf is generated. I do not know if there is a crazy lag time and that is affecting the button from the GUI or what, but some svg might take upwards of 30 clicks on the export button, and others never produce a pdf at all. Is there any way to better understand what is going on with the pdf export to know if it is working at all, so I know if it is a GUI or library issue?</p>

<p>Any ideas are appreciated!</p>

<pre><code>import controlP5.*; //add the GUI library
import drop.*; //add the drag and drop library
import processing.pdf.*; //add the pdf library

SDrop drop; //make an instance of the sDrop library

PShape myShape; //make a shape variable to hold the svg file

ControlFrame cf; //will help us make a second window for the controls

int space = 40; //some initial settings = spacing
float scl = 40.0; //the scale of each object
float noiseScale = 200.0; //the scale of the noise (how smooth)
float noiseEffect = 0.0; //the strength of the noise affecting the position
float noiseRot = 0.0; //the strength of the noise affecting the rotation
float seed = 1; //the noise seed
boolean pdf = false;
int pdfCount = 1; //starting number for the exported pdf

void settings(){
  size(800, 800); //setup our stage/canvas
}

void setup(){
  noFill();
  smooth();
  rectMode(CENTER); //for the starting rectangles, center them
  cf = new ControlFrame(this, 300, 300, "Controls"); //make a new window at 300 wide and 300 tall
  surface.setLocation(320, 10); //move the main window over to make room for the control window
  drop = new SDrop(this); //setup the drag and drop
}

void draw(){
  background(255);

  if(pdf)beginRecord(PDF, "pattern" + pdfCount + ".pdf"); //if the button is pressed, begin recording to make the pdf
  noFill();
  for(int x = space/2; x &lt; width; x+= space) { //iterate across the canvas
    for(int y = space/2; y &lt; width; y+= space) { //iterate down the canvas
      float nx = x + noiseEffect * 2*(noise(seed, y/noiseScale, x/noiseScale)-0.5); //compute the x position noise
      float ny = y + noiseEffect * 2*(noise(x/noiseScale, seed, y/noiseScale)-0.5); //compute the y position noise
      float rot = 4 * PI * (noise(x/noiseScale, y/noiseScale, seed)-0.5) * noiseRot; //compute the rotation noise
      pushMatrix();
      translate(nx, ny); //move the shape into place
      rotate(rot); //rotate the shape
      //scale(scl);
      if(myShape !=null){ //if we have dropped on an svg, then use it
        shape(myShape, 0, 0, scl, scl); //draw the svg
      }else{
        rect(0, 0, scl, scl); //otherwise, use some squares
        //ellipse(0, 0, scl, scl); //or some ellipses
      }
      popMatrix();
    }
  }
  if(pdf) {
    endRecord();
    pdfCount++;
    pdf = false;
  }
}

void dropEvent(DropEvent theDropEvent) { //this takes care of the drag and drop
   if(theDropEvent.isFile()) {
    // for further information see
    // <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/io/File.html" target="_blank" rel="nofollow">http://java.sun.com/j2se/1.4.2/docs/api/java/io/File.html</a>
      String myFile = theDropEvent.filePath(); //get the filepath
      myShape = loadShape(myFile); //load the svg into our shape variable
   }
}

//everything below this makes the control window

class ControlFrame extends PApplet {

  int w, h;
  PApplet parent;
  ControlP5 cp5;

  public ControlFrame(PApplet _parent, int _w, int _h, String _name) {
    super();   
    parent = _parent;
    w=_w;
    h=_h;
    PApplet.runSketch(new String[]{this.getClass().getName()}, this);
  }

  public void settings() {
    size(w, h);
  }

  public void setup() {
    surface.setLocation(10, 10);
    cp5 = new ControlP5(this);

    cp5.addSlider("spacing")
       .plugTo(parent, "space")
       .setRange(1, 400)
       .setValue(40)
       .setPosition(20, 20)
       .setSize(200, 30);

    cp5.addSlider("scaling")
       .plugTo(parent, "scl")
       .setRange(10.0, 400.0)
       .setValue(40.0)
       .setPosition(20, 60)
       .setSize(200, 30); 

    cp5.addSlider("noise scale")
       .plugTo(parent, "noiseScale")
       .setRange(20.0, 1000.0)
       .setValue(200.0)
       .setPosition(20, 100)
       .setSize(200, 30);

    cp5.addSlider("noise effect - pos")
       .plugTo(parent, "noiseEffect")
       .setRange(0.0, 300.0)
       .setValue(0.0)
       .setPosition(20, 140)
       .setSize(200, 30);

    cp5.addSlider("noise effect - rot")
       .plugTo(parent, "noiseRot")
       .setRange(0.0, 1.0)
       .setValue(0.0)
       .setPosition(20, 180)
       .setSize(200, 30);

    cp5.addSlider("noise seed")
       .plugTo(parent, "seed")
       .setRange(0.0, 10.0)
       .setValue(0.0)
       .setPosition(20, 220)
       .setSize(200, 30);

    cp5.addButton("exportPDF")
       .plugTo(parent, "pdf")
       .setSwitch(false)
       .setPosition(20, 260)
       .setSize(50, 30);
  }

  void draw() {
    background(190);
  }

}
</code></pre>
]]></description>
   </item>
   <item>
      <title>How to use P3d with contorl P5 GUI library?</title>
      <link>https://forum.processing.org/two/discussion/25573/how-to-use-p3d-with-contorl-p5-gui-library</link>
      <pubDate>Fri, 15 Dec 2017 00:54:30 +0000</pubDate>
      <dc:creator>joannajoanna</dc:creator>
      <guid isPermaLink="false">25573@/two/discussions</guid>
      <description><![CDATA[<p>****Hi, I am new to processing and am using processing 3.3.6</p>

<p>Wondering if anyone can help me make the GUI interface render in 2D ?</p>

<p>The idea is to have a sphere in the middle (able to rotate with mouseX,Y -&gt;using peacy cam) and on click GUI button will render 2D pattern(ellipse for example) on the canvas and play sound</p>

<p>Below is my code:</p>

<pre><code>import peasy.*;

!import processing.sound.*;

import controlP5.*;

ControlP5 cp5;


PeasyCam cam;

PVector [][] globe;

int total = 100;
</code></pre>

<p>// button data</p>

<pre><code>  Button pollution;
</code></pre>

<p>// --- set up control</p>

<pre><code> boolean populationpatternon = true;
 boolean deathpatternon = true;
 boolean socialpatternon = true;
 boolean pollutionpatternon = true;


void setup(){
  size(1000,1000,P3D);
  hint(ENABLE_DEPTH_TEST);
  globe = new PVector[total][total];
  cam = new PeasyCam(this,200);
  hint(DISABLE_DEPTH_TEST);

  cp5 = new ControlP5(this);
  pollution = cp5.addButton("pollution").setValue(0).activateBy(ControlP5.RELEASE);

}

public void pollution(){
  println("Button Pressed pollution");
  pollutionpatternon = !pollutionpatternon;
}

void draw(){
  background(255);
  lights();
  lightSpecular(255, 255, 255); 
  directionalLight(255, 255, 255, 1, 1, -1); 
  drawsphere(); 


  if(pollutionpatternon == true){
    pollutionpattern();
  }
}

void drawsphere(){
  lights();
  float r = 50;

  for(int i = 0; i &lt; total; i ++){ 
    float lat = map(i, 0,total,-HALF_PI,HALF_PI); 
    for(int j = 0; j &lt;total; j ++){
    float lon = map(j, 0,total,-PI,PI);
    float x = r * sin(lon)*cos(lat);
    float y = r * sin(lon)*sin(lat);
    float z = r * cos(lon);
    globe[i][j] = new PVector(x,y,z);
    }
  }
  for(int i = 0; i &lt; total; i ++){  
    for(int j = 0; j &lt;total; j ++){
    PVector v = globe[i][j];
    stroke(20);
    strokeWeight(2);
    point(v.x, v.y, v.z);
    }
  }
}

void pollutionpattern(){
  ellipse(300,100,100,100);
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Vertical tabs with the controlp5 library</title>
      <link>https://forum.processing.org/two/discussion/23306/vertical-tabs-with-the-controlp5-library</link>
      <pubDate>Tue, 04 Jul 2017 10:48:08 +0000</pubDate>
      <dc:creator>Mica_S</dc:creator>
      <guid isPermaLink="false">23306@/two/discussions</guid>
      <description><![CDATA[<p>Hello guys!
I'm totally new to this forum and I'm sorry if this question above was asked before in an other threat. But asking google and browsing this forum did not help very much!</p>

<p>So:</p>

<p>Is it possible to make vertical tabs with the controlp5 library? I want to make many of them so there is not enough space horizontally.</p>

<p>And ist it possible that the tab is a button at the same time?</p>

<p>Currently I'm working with the example Code from the controlp5 library:</p>

<pre><code>/**
* ControlP5 Tab
*
*
* find a list of public methods available for the Tab Controller
* at the bottom of this sketch.
*
* by Andreas Schlegel, 2012
* www.sojamo.de/libraries/controlp5
*
*/

import controlP5.*;

ControlP5 cp5;

int myColorBackground = color(128);

int sliderValue = 100;

void setup() {
  size(700,400);
  noStroke();
  cp5 = new ControlP5(this);

  // By default all controllers are stored inside Tab 'default' 
  // add a second tab with name 'extra'

  cp5.addTab("extra")
     .setColorBackground(color(0, 160, 100))
     .setColorLabel(color(255))
     .setColorActive(color(255,128,0))
     ;

  // if you want to receive a controlEvent when
  // a  tab is clicked, use activeEvent(true)

  cp5.getTab("default")
     .activateEvent(true)
     .setLabel("my default tab")
     .setId(1)
     ;

  cp5.getTab("extra")
     .activateEvent(true)
     .setId(2)
     ;


  // create a few controllers

  cp5.addButton("button")
     .setBroadcast(false)
     .setPosition(100,100)
     .setSize(80,40)
     .setValue(1)
     .setBroadcast(true)
     .getCaptionLabel().align(CENTER,CENTER)
     ;

  cp5.addButton("buttonValue")
     .setBroadcast(false)
     .setPosition(220,100)
     .setSize(80,40)
     .setValue(2)
     .setBroadcast(true)
     .getCaptionLabel().align(CENTER,CENTER)
     ;

  cp5.addSlider("slider")
     .setBroadcast(false)
     .setRange(100,200)
     .setValue(128)
     .setPosition(100,160)
     .setSize(200,20)
     .setBroadcast(true)
     ;

  cp5.addSlider("sliderValue")
     .setBroadcast(false)
     .setRange(0,255)
     .setValue(128)
     .setPosition(100,200)
     .setSize(200,20)
     .setBroadcast(true)
     ;

  // arrange controller in separate tabs

  cp5.getController("sliderValue").moveTo("extra");
  cp5.getController("slider").moveTo("global");

  // Tab 'global' is a tab that lies on top of any 
  // other tab and is always visible

}

void draw() {
  background(myColorBackground);
  fill(sliderValue);
  rect(0,0,width,100);
}

void controlEvent(ControlEvent theControlEvent) {
  if (theControlEvent.isTab()) {
    println("got an event from tab : "+theControlEvent.getTab().getName()+" with id "+theControlEvent.getTab().getId());
  }
}

void slider(int theColor) {
  myColorBackground = color(theColor);
  println("a slider event. setting background to "+theColor);
}


void keyPressed() {
  if(keyCode==TAB) {
    cp5.getTab("extra").bringToFront();
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Initialize function with CP5 button</title>
      <link>https://forum.processing.org/two/discussion/22636/initialize-function-with-cp5-button</link>
      <pubDate>Wed, 17 May 2017 12:52:04 +0000</pubDate>
      <dc:creator>kasperrubin</dc:creator>
      <guid isPermaLink="false">22636@/two/discussions</guid>
      <description><![CDATA[<p>I have this code that draws hexagons randomly in a grid and coloring them randomly from an array.</p>

<p>What I want to do is press a CP5 button to initialize the drawing function. If I press this button again, it will fill all drawn hexagons with black and re-initialize the drawing function.</p>

<p>Currently this controls the drawing:</p>

<pre><code>void mousePressed() {

  if (active_counter == 0) {

    hexagons[int(wide/2)][int(tall/2)].active = true;

    active_counter++;
  }
}
</code></pre>

<p>So I tried this approach:</p>

<pre><code>public void startDrawing(int theValue) {
    println("a button event from startDrawing: "+theValue);
    c1 = c2;
    c2 = color(0,0,0);

    if (active_counter == 40) {
      fill(color(0));
    }
}
</code></pre>

<p>Now, I know this is not working, because “fill” is not connected to “hexagons”, but I have difficulty appending it the right way.</p>

<p>This is the full code:</p>

<pre><code>import controlP5.*;

ControlP5 cp5;

int myColor = color(255);

int c1,c2;

float n,n1;

// ------------- Hexagon grid -------------
Hexagon[] [] hexagons;

float rx = 51;
float ry = 56;
int wide;
int tall;

int hexagon;

int active_counter = 0;
boolean active;
int max_hexagons;

float Xoffset, Yoffset;
int randX;
int randY;
int randD;
int x;
int y;

int[] stepX = { -1, -1, 1, 0, 1, 1 };
int[][] stepY = {{ 0, 1, -1, 1, 0, 1 }, { 0, -1, -1, 1, 0, -1 } };

class Hexagon {
  float x;
  float y;
  int rand;
  color[] colors;
  boolean active;

  Hexagon (float ix, float iy) {
    x = ix;
    y = iy;
    active = false;

    // Array of colors
    colors = new color[10];
    colors[0] = color(#62563D); // Infantry green
    colors[1] = color(#2C2B2D); // Parisian night blue
    colors[2] = color(#3E2224); // Purple heart
    colors[3] = color(#A49F9B); // Wild dove grey
    colors[4] = color(#684F40); // Brown
    colors[5] = color(#5C573D); // Moss green
    colors[6] = color(#B9897F); // Pink
    colors[7] = color(#24283B); // Dark blue
    colors[8] = color(#1F1D20); // Black
    colors[9] = color(#C5A9A2); // Brazilian clay

    // Takes the colors array and output random colors
    rand = (int)random(colors.length);
  }
  // ------------- Nested draw -------------
  void draw() {
    if (active) {

      // Call the colors array in random order
      fill(colors[rand]);
    } else {
      noFill();
    }

    stroke(80);
    pushMatrix();
    translate(x, y);
    beginShape();
    vertex(-17, -28);
    vertex(17, -28);
    vertex(34, 0);
    vertex(17, 28);
    vertex(-17, 28);
    vertex(-34, 0);
    endShape(CLOSE);
    popMatrix();
  }
}

// ------------- setup -------------
void setup() {
  size(1000, 700);

  // ------------- CP5 control buttons -------------
  cp5 = new ControlP5(this);

  cp5.addButton("start drawing")
     .setValue(0)
     .setPosition(20,80)
     .setSize(200, 19)
     ;

  // ------------- Create hexagon grid -------------
  wide = int(width/rx) + 2;

  tall = int (height/ry) + 2;

  max_hexagons = 40;

  hexagons = new Hexagon [wide] [tall];

  for (int y = 0; y &lt; tall; y++) {
    for (int x = 0; x &lt; wide; x++) {

      if ( x % 2 == 0) {

        hexagons[x] [y] = new Hexagon(x*rx, y*ry);

      } else {

        hexagons[x] [y] = new Hexagon(x*rx, (y-.5)*ry);
      }
    }
  }

  float targetX = width/2;
  float targetY = height/2;

  Xoffset = hexagons [int(wide/2)] [int(tall/2)] .x - targetX;
  Yoffset = hexagons [int(wide/2)] [int(tall/2)] .y - targetY;
}

// ------------- draw -------------
void draw () {
  background(0);
  pushMatrix();
  translate(-Xoffset, -Yoffset);
  for (int y = 0; y &lt; tall; y++) {
    for (int x = 0; x &lt; wide; x++) {

      hexagons[x] [y] .draw();
    }
  }
  if (active_counter &gt; 0 &amp;&amp; active_counter &lt; max_hexagons) {
    nextHex();
  }
  popMatrix();
  myColor = lerpColor(c1,c2,n);
    n += (1-n)* 0.1; 
} 
  public void controlEvent(ControlEvent theEvent) {
    println(theEvent.getController().getName());
    n = 0;
  }

  public void startDrawing(int theValue) {
    println("a button event from startDrawing: "+theValue);
    c1 = c2;
    c2 = color(0,0,0);

    if (active_counter == 40) {
      fill(color(0));
    }

  }

// ------------- Mouse interaction -------------
void mousePressed() {

  if (active_counter == 0) {

    hexagons[int(wide/2)][int(tall/2)].active = true;

    active_counter++;
  }
}

// ------------- Drawing next hexagon -------------
void nextHex() {
  int randX = int(random(wide));
  int randY = int(random(tall));
  while (!hexagons[randX][randY] .active) {
    randX = int(random(wide));
    randY = int(random(tall));
  } 
  int randD = int(random(6));
  if (
    randX + stepX[randD] &gt;= 0 &amp;&amp; 
    randX + stepX[randD] &lt; wide &amp;&amp;
    randY + stepY[randX % 2][randD] &gt;= 0 &amp;&amp; 
    randY + stepY[randX % 2][randD] &lt; tall
    ) {
    if (!hexagons[randX + stepX[randD]][randY + stepY[randX % 2][randD]] .active) {
      active_counter++;
    }
    hexagons[randX + stepX[randD]][randY + stepY[randX % 2][randD]] .active = true;
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>saveFrame function inconsistency</title>
      <link>https://forum.processing.org/two/discussion/22498/saveframe-function-inconsistency</link>
      <pubDate>Wed, 10 May 2017 14:54:23 +0000</pubDate>
      <dc:creator>ProcessoRas</dc:creator>
      <guid isPermaLink="false">22498@/two/discussions</guid>
      <description><![CDATA[<p>Hello guys! Need some help!</p>

<p>I am trying to use save frame to take a screenshot of a plot I have currently programmed with processing. The plot GUI has several Buttons (made with Cp5) and Toggles. I have set a function which is being called when a button is pressed. However, sometime the frame I take comes with the cp5 buttons GUI but sometimes doesn't. So some frames have the buttons but some don't. For example:
<img src="" alt="" /><img src="https://forum.processing.org/two/uploads/imageupload/168/B6EFLAGR4GAR.jpg" alt="2017_05_10-17_26_38113" title="2017_05_10-17_26_38113" /></p>

<p><img src="https://forum.processing.org/two/uploads/imageupload/781/IU1C2WX7FFAW.jpg" alt="2017_05_10-17_26_40115" title="2017_05_10-17_26_40115" /></p>

<p>Hope, you can see the frames. The code I use for the button is:</p>

<pre><code>Button b1 = cp5.addButton("takeScreenShot").setPosition(z, w).setSize(100, 80);

  b1.addCallback(new CallbackListener() {
    public void controlEvent(CallbackEvent theEvent) {
      switch(theEvent.getAction()) { 
        case(ControlP5.ACTION_PRESSED): 
        if (flag) {
          println("Taking photo...");
          takeScreenShot();
        }
        break;
         case(ControlP5.ACTION_RELEASED): 
         println("Done");
         flag = true;
         break;
      }
    }
  }
  );
</code></pre>

<p>and the function called for the takeFrame():</p>

<pre><code>void takeScreenShot() {
      String photoDate = new SimpleDateFormat("yyyy_MM_dd-HH_mm_ss").format(new Date());
      String Date = new SimpleDateFormat("yyyy_MM_dd").format(new Date());
      int m = millis()/1000; //for seconds
      saveFrame("C:/Users/. . . .. . ./data/"+ Date + "/photos/" +  "/manual/"+ photoDate + String.valueOf(m)+ ".jpg");
    }
</code></pre>

<p>Is there any suggestions on how to tackle this problem?? I would appreciate any help, and any clarifications if needed.</p>

<p>ps. If the photos don't show, the buttons from cp5 configurations sometimes show sometimes don't. Can't find any reason why.!</p>
]]></description>
   </item>
   <item>
      <title>Checking Whether Button Was Pressed or not?</title>
      <link>https://forum.processing.org/two/discussion/22143/checking-whether-button-was-pressed-or-not</link>
      <pubDate>Sat, 22 Apr 2017 21:57:06 +0000</pubDate>
      <dc:creator>kloud</dc:creator>
      <guid isPermaLink="false">22143@/two/discussions</guid>
      <description><![CDATA[<p>I just need some help with checking whether or not this button was pressed. If its pressed I will have to write to the servo, instead of writing to the servo automatically.</p>

<pre><code>import processing.serial.*;          //imports serail library
import cc.arduino.*;                 //imports arduino library so I don't have to use arduino IDE
import controlP5.*;                  //Part of processing library


Arduino arduino;
ControlP5 cp5;

Slider Servo1;

void setup() 
{
  size(950, 900);

  println(Arduino.list());                                  //sends data to serial port for arduino
  arduino = new Arduino(this, Arduino.list()[0], 57600);    //sets COMM Port Baud Rate
  cp5 = new ControlP5(this);                                //dynamic variable of control class

  arduino.pinMode(3, Arduino.SERVO);

 Servo1 = cp5.addSlider(".").setRange(0,180).setValue(90).setPosition(110,134).setSize(270,25).setNumberOfTickMarks(270).setLabelVisible(true).setColorForeground(color(102,102,102)).setColorBackground(color(255,153,0)).setColorActive(color(102,102,102));
cp5.addButton("PressButton")
     .setValue(1)
     .setPosition(400,600);
 }

void draw() 
{
 arduino.servoWrite(3, int(Servo1.getValue()));
 }
</code></pre>
]]></description>
   </item>
   <item>
      <title>Making a back button</title>
      <link>https://forum.processing.org/two/discussion/21800/making-a-back-button</link>
      <pubDate>Tue, 04 Apr 2017 13:37:19 +0000</pubDate>
      <dc:creator>taarons</dc:creator>
      <guid isPermaLink="false">21800@/two/discussions</guid>
      <description><![CDATA[<p>My code is a little long so I'm sorry about that but I've tried to condense it here and just explain the bare minimum of my problem. I have a state machine that incorporates both mousePressed and button functions. I want to create a back button starting in state 2, so I called it in one of my state 2 options,  void showQuestion2Palestinian(). The problem is, it only shows up if I click the Palestinian button first. Additionally, I had to put a set of conditions on the button more specific than state--; because I don't always just want it to go back to the last state. I've given it direct assignments, but a couple of them glitch and don't go back to the right state. I don't know if this is a flaw in my processing application or in the code... Please help!</p>

<pre><code>import controlP5.*;
ControlP5 cp5session1;
ControlP5 cp5session2;
ControlP5 cp5session3;
ControlP5 cp5;

int state;

void setup() { 
  size(800, 600);
  background(255);  
}

void mousePressed() {

  if(state == 3) {
    if (200&lt;mouseX &amp;&amp; mouseX&lt;400 &amp;&amp; 100&lt;mouseY &amp;&amp; mouseY&lt;400){
    state = 4;  
    }
  }

/*  if(state == 4) {
    if (200&lt;mouseX &amp;&amp; mouseX&lt;400 &amp;&amp; 100&lt;mouseY &amp;&amp; mouseY&lt;400){
    state = 5;  
    }
  } */

  if(state == 6) {
    if (200&lt;mouseX &amp;&amp; mouseX&lt;400 &amp;&amp; 100&lt;mouseY &amp;&amp; mouseY&lt;400){
    state = 7;  
    }
  }
   if(state == 8) {
    if (0&lt;mouseX &amp;&amp; mouseX&lt;800 &amp;&amp; 0&lt;mouseY &amp;&amp; mouseY&lt;600){
    state = 9;  
    }
  }
  if(state == 10) {
    //should be before
    if (200&lt;mouseX &amp;&amp; mouseX&lt;400 &amp;&amp; 100&lt;mouseY &amp;&amp; mouseY&lt;400){
    state = 12;  
    }
  }

  /*if(state == 11) {
    if (200&lt;mouseX &amp;&amp; mouseX&lt;400 &amp;&amp; 100&lt;mouseY &amp;&amp; mouseY&lt;400){
    state = 12;  
    }
  } */

  if(state == 13) {
    if (200&lt;mouseX &amp;&amp; mouseX&lt;400 &amp;&amp; 100&lt;mouseY &amp;&amp; mouseY&lt;400){
    state = 14;  
    }
  }
   if(state == 15) {
    if (0&lt;mouseX &amp;&amp; mouseX&lt;800 &amp;&amp; 0&lt;mouseY &amp;&amp; mouseY&lt;600){
    state = 16;  
    }
  } 
}


public void Next (int theValue) {
  println("a button event from Next: "+theValue);
  showQuestion1();
  state++;
}

void showQuestion1() {
  background(255);
  video.stop();
  cp5.hide();

  cp5session1 = new ControlP5(this); 

  cp5session1.addButton("Palestinian")
    .setPosition(width/2 - 200, 285)
    .updateSize()
    .setSize(100, 50)
    ;

  cp5session1.addButton("Israeli")
    .setPosition(width/2 + 100, 285)
    .updateSize()
    .setSize(100, 50)
    ;

}

public void controlEvent(ControlEvent theEvent) {
  println(theEvent.getController().getName());
}

public void Palestinian (int theValue) {
  println("a button event from Palestinian: "+theValue);
  showQuestion2Palestinian();
  state = 2;
}

public void Israeli (int theValue) {
  println("a button event from Israeli: "+theValue);
  showQuestion2Israeli();
  state = 2;

}


void showQuestion2Palestinian() {
  background(0);
  cp5session1.hide();

  //Date buttons created 
  cp5session2 = new ControlP5(this);
  cp5session2.addButton("Palestine1945")
    .setPosition(width/3 - 100, 285)
    .updateSize()
    .setSize(100, 50)
    ;

  cp5session2.addButton("Palestine1967")
    .setPosition(width/3 + 100, 285)
    .updateSize()
    .setSize(100, 50)
    ;

  cp5session2.addButton("Palestine2017")
    .setPosition(width/3 + 300, 285)
    .updateSize()
    .setSize(100, 50)
    ;

cp5session3 = new ControlP5(this); 

  cp5session3.addButton("back")
    .setPosition(600, 500)
    .updateSize()
    .setSize(100, 50)
    ;
}


public void back (int theValue) {
  println("a button event from Palestine 1945: "+theValue);

  if (state == 2) {
    state--;
    cp5session1.show();
    cp5session2.hide();
  }
   if (state == 3) {
    state = 2;
  }
   if (state == 4) {
    state = 3;
  }
   if (state == 5) {
    state = 4;
  }
   if (state == 6) {
    state = 2;
  }
   if (state == 7) {
    state = 6;
  }
   if (state == 8) {
    state = 2;
  }

   if (state == 9) {
    state = 8;
  }
   if (state == 10) {
    state = 2;
  }

   if (state == 11) {
    state = 10;
  }

   if (state == 12) {
    state = 11;
  }

   if (state == 13) {
    state = 2;
  }
   if (state == 14) {
    state = 13;
  }

   if (state == 15) {
    state = 2;
  }

   if (state == 16) {
    state = 15;
  }
}

public void Palestine1945 (int theValue) {
  println("a button event from Palestine 1945: "+theValue);
  state = 3;
  cp5session2.hide();
  cp5session1.hide();

}

public void Palestine1967 (int theValue) {
  println("a button event from Palestine1967: "+theValue);
  state = 6;
  cp5session2.hide();
  cp5session1.hide();

}


public void Palestine2017 (int theValue) {
  println("a button event from Palestine2017: "+theValue);
  state = 8; 
  cp5session2.hide();
  cp5session1.hide();

}

void showQuestion2Israeli() {
  background(255);
  cp5session1.hide();
  //cp5session3.show(); &lt;== when I run this, the buttons don't show up at all 

  cp5session2 = new ControlP5(this);

  cp5session2.addButton("Israel1945")
    .setPosition(width/3 - 100, 285)
    .updateSize()
    .setSize(100, 50)
    ;

  cp5session2.addButton("Israel1967")
    .setPosition(width/3 + 100, 285)
    .updateSize()
    .setSize(100, 50)
    ;

  cp5session2.addButton("Israel2017")
    .setPosition(width/3 + 300, 285)
    .updateSize()
    .setSize(100, 50)
    ;
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>ControlP5 setLock(true) doesn't work when Button is under mouse</title>
      <link>https://forum.processing.org/two/discussion/21706/controlp5-setlock-true-doesn-t-work-when-button-is-under-mouse</link>
      <pubDate>Thu, 30 Mar 2017 15:35:47 +0000</pubDate>
      <dc:creator>stefandz</dc:creator>
      <guid isPermaLink="false">21706@/two/discussions</guid>
      <description><![CDATA[<p>Not sure if I am being completely daft here, but I am finding an issue where using setLock(true) to disable a ControlP5 button works only if the button you are modifying doesn't have the mouse over it when setLock(true) is called. Example code (originally by <a href="/two/profile/andreas">@andreas</a>.schlegel from his answer <a rel="nofollow" href="https://forum.processing.org/one/topic/controlp5-disable-gui-elements.html#25080000000975458">here</a>)</p>

<pre><code>import controlP5.*;

ControlP5 controlP5;
int col;

void setup() {
  size(640,480);
  smooth();
  frameRate(30);
  controlP5 = new ControlP5(this);
  controlP5.addButton("buttonA",0,100,100,80,19);
  controlP5.addButton("buttonB",255,100,120,80,19);
  controlP5.addButton("buttonC",128,100,140,80,19);

  // store the original background color, we gonna need it later
  col = controlP5.getController("buttonC").getColor().getBackground();
  // lock Controller 'buttonC'
  setLock(controlP5.getController("buttonC"),true);
}


void setLock(Controller theController, boolean theValue) {
  theController.setLock(theValue);
  if(theValue) {
    theController.setColorBackground(color(100,100));
  } else {
    theController.setColorBackground(color(col));
  }
}

void keyPressed() {
  // temporarily enable/disable Controller 'buttonC'
  if(key=='1') {
    setLock(controlP5.getController("buttonC"), false);
  } else if(key=='2') {
    setLock(controlP5.getController("buttonC"), true);
  }
}

void draw() {
  background(0);
}

public void controlEvent(ControlEvent theEvent) {
  println(theEvent.controller().getName());
}
</code></pre>

<p>Run this and use the 1 and 2 keys to unlock and lock buttonC. Works well, except if you leave your mouse hovering over the buttonC while pressing 1 and 2. Has anyone come across this before? Is there a workaround? I am happy to try and work out a fix if anyone has any idea roughly where within ControlP5 to go hunting for this!!</p>

<p>FWIW I am using Processing 3.2.3 and ControlP5 2.2.6</p>
]]></description>
   </item>
   <item>
      <title>Show/Hide CP5 Button</title>
      <link>https://forum.processing.org/two/discussion/21667/show-hide-cp5-button</link>
      <pubDate>Tue, 28 Mar 2017 22:07:51 +0000</pubDate>
      <dc:creator>taarons</dc:creator>
      <guid isPermaLink="false">21667@/two/discussions</guid>
      <description><![CDATA[<p>Hi! I'm new to coding so sorry if this question is dumb but I can't figure out how to make a CP5 button hide once it's been clicked. I want the two buttons A and B to be the first to show then once they are clicked I want the buttons 1945, 1960, and 2015 to show and A and B to hide. Please help!</p>

<p>import controlP5.*;</p>

<pre><code>ControlP5 cp5;

String myResponse1;
int myResponse2;
PImage show1947Israel, show1960Israel, show2015Israel, question;
boolean display = false;

void setup() {
  size(600, 600);
  background(255);

  cp5 = new ControlP5(this);

  cp5.addButton("A")
     .setPosition(210,300)
     .updateSize()
     ;

  cp5.addButton("B")
  .setPosition(310,300)
     .updateSize()
     ;

  cp5.addButton("1945")
     .setPosition(150,400)
     .updateSize()
     ;

cp5.addButton("1945").setSwitch(true);

  cp5.addButton("1960")
     .setPosition(250,400)
     .updateSize()
     ;

cp5.addButton("1960").setSwitch(true);

  cp5.addButton("2015")
     .setPosition(350,400)
     .updateSize()
     ;

cp5.addButton("2015").setSwitch(true);

question = loadImage("when.png");
show1947Israel = loadImage("1947map.png");
show1960Israel = loadImage("1960map.png");
show2015Israel = loadImage("2015map.png");

}

void draw(){
  hideButton();

}  

void hideButton() {
 if (display == false) {
    cp5.addButton("1945").hide();
    cp5.addButton("1960").hide();
    cp5.addButton("2015").hide();
  }
  else {
   cp5.addButton("1945").show();
   cp5.addButton("1960").show();
   cp5.addButton("2015").show();
  }
}
  public void controlEvent(ControlEvent theEvent) {
  println(theEvent.getController().getName());
  }

// function A will receive changes from 
// controller with name A
  public void A(int theValue) {
  println("a button event from A: "+theValue);
 showQuestion2();


  }
// function B will receive changes from 
// controller with name B
  public void B(int theValue) {
  println("a button event from B: "+theValue);
showQuestion2();
  }

  void showQuestion2() {
   image(question, 0, 0, width, height);
   display = true;
  }
</code></pre>
]]></description>
   </item>
   <item>
      <title>Trying to create multiple arms, with differente segments size, using controlP5 Library.</title>
      <link>https://forum.processing.org/two/discussion/21517/trying-to-create-multiple-arms-with-differente-segments-size-using-controlp5-library</link>
      <pubDate>Tue, 21 Mar 2017 13:40:01 +0000</pubDate>
      <dc:creator>Rperes2000</dc:creator>
      <guid isPermaLink="false">21517@/two/discussions</guid>
      <description><![CDATA[<p>Trying to create multiple arms, with different  segments size, using controlP5 Library to create a easy 'robot arm drive simulator', but the code only work if all arm are equal in segment size. If not we get a a arm segments Overlap!!</p>

<p>Could you give me a topic just to fixe my code?</p>

<p>Tks in advance.
Jose Peres.</p>

<p>// JPeres: 20-MAR-2017
import controlP5.*;
ControlP5 cp5;</p>

<p>float x, y;
float angle1, angle2, angle3 = 0.0;</p>

<p>float segLength  = 100;
float segLength1 = 100; // Must be equal to var segLength!!! - How to fix ?? 
float segLength2 = 100; // Must be equal to var segLength!!! - How to fix ??</p>

<p>int V01 = 0;
int V02 = 0;
int V03 = 0;</p>

<p>void setup() {
  size(1080, 640);
  strokeWeight(25);
  stroke(255, 160);</p>

<p>x = width * 0.40;
  y = height * 0.7;</p>

<p>cp5 = new ControlP5(this);</p>

<p>cp5.addSlider("V01")
    .setPosition(900, 80)
    .setSliderMode(Slider.FLEXIBLE)
    .setValue(0)
    .setSize(20, 300)
    .setRange(-90, 90);</p>

<p>cp5.addSlider("V02")
    .setPosition(940, 80)
    .setSliderMode(Slider.FLEXIBLE)
    .setValue(0)
    .setSize(20, 300)
    .setRange(-90, 90);</p>

<p>cp5.addSlider("V03")
    .setPosition(980, 80)
    .setSliderMode(Slider.FLEXIBLE)
    .setValue(0)
    .setSize(20, 300)
    .setRange(-90, 90);</p>

<p>cp5.addSlider("H00")
    .setPosition(280, height-40)
    .setSliderMode(Slider.FLEXIBLE)
    .setValue(0)
    .setSize(300, 30)
    .setRange(-90, 90);</p>

<p>cp5.addButton("ARM_RESET")
    .setPosition(900, height-100)
    .setSize(140, 40)
    .setValue(0)
    .activateBy(ControlP5.RELEASE);</p>

<p>cp5.addButton("ARM_HOME")
    .setPosition(900, height-50)
    .setSize(140, 40)
    .setValue(0)
    .activateBy(ControlP5.RELEASE);
}
void draw() {
  background(80);
  angle1 = ((-V01+90)/float(180)) * -PI;
  angle2 = (-90+V02/float(180)) * PI;</p>

<p>pushMatrix();
  segment(x, y, angle1); 
  segment(segLength1, 0, angle2);
  segment(segLength2, 0, angle3);</p>

<p>popMatrix();
  line(x, y, x, y+80);
  rect(0, y+80, width, y+80);
}
void segment(float x, float y, float a) {
  translate(x, y);
  rotate(a);
  line(0, 0, segLength, 0);
}
public void ARM_RESET(int value) {
  cp5.getController("V01").setValue(0);
  cp5.getController("V02").setValue(0);
  cp5.getController("V03").setValue(0);
  cp5.getController("H00").setValue(0);
}
public void ARM_HOME(int value) {
  cp5.getController("V01").setValue(90);
  cp5.getController("V02").setValue(-90);
  cp5.getController("V03").setValue(-90);
  cp5.getController("H00").setValue(0);
}
// That's the end!</p>
]]></description>
   </item>
   <item>
      <title>How to take data from a ControlP5 scrollable list, and use it to select a row in spreadsheet?</title>
      <link>https://forum.processing.org/two/discussion/21226/how-to-take-data-from-a-controlp5-scrollable-list-and-use-it-to-select-a-row-in-spreadsheet</link>
      <pubDate>Tue, 07 Mar 2017 16:27:20 +0000</pubDate>
      <dc:creator>Attrup</dc:creator>
      <guid isPermaLink="false">21226@/two/discussions</guid>
      <description><![CDATA[<p>Hello
I'm trying to make a program which calculates values which it gets from a spreadsheet. I'm using a ControlP5 scrollable list to show all the possible selection. Each item in the list represents a row in the spreadsheet. To each row there is 7 columns.</p>

<p>So my question is how do i let processing know or rather code, that the item selected in the list is a row in the spreadsheet? It's very poorly explained i know, but i will try to explain further if need! Thank you so much in advance!</p>

<p>A simplified version of my code:</p>

<p>`</p>

<pre><code>    import controlP5.*;
    import java.util.*;

    ControlP5 cp5;

    ScrollableList initialBodyList;

    Button butDeltaVplanet;

    Table Planeter;

    Textfield required_delta_V;

    void setup() {
      size(500, 500);
      cp5 = new ControlP5(this);

       Planeter = loadTable("DatasheetPlanets.csv", "header");

      butDeltaVplanet = cp5.addButton("Calculate required Delta V")
        .setPosition(300, 50)
        .setColorForeground(#EA0037)
        .setColorActive(#FF4343)
        .setSize(130, 30);
      List body = Arrays.asList("Kerbol", "Moho", "Eve", "     Gilly", "Kerbin", "     Mun", "     Minmus", "Duna", "     Ike", "Dres", "Jool", "     Laythe", "     Vall", "     Tylo", "     Bop", "     Pol", "Eeloo");

      initialBodyList = cp5.addScrollableList("Initial body")
        .setPosition(70, 50)
        .setSize(200, 300)
        .setBarHeight(30)
        .setItemHeight(20)
        .setBackgroundColor(#EA0037)
        .setColorForeground(#EA0037)
        .setColorActive(#FF4343)
        .addItems(body)
        .setOpen(false);

      required_delta_V = cp5.addTextfield("Required Delta V m/s")
        .setPosition(300, 120)
        .setSize(130, 30);


      ControlP5.printPublicMethodsFor(Textfield.class);
    }

    void draw() {
      background(200);
    }

    public void controlEvent(ControlEvent theEvent) {

      if (theEvent.isFrom(butDeltaVplanet)) {

        int planet1 = Planeter.getRow(3).getInt("DeltaVtoKerbinorbit");

        int planet2 = Planeter.getRow(4).getInt("DeltaVtoKerbinorbit");

        float deltaV = 0;

        deltaV = planet1 + planet2;

        required_delta_V.setText("   " + deltaV);
      }
    }`
</code></pre>
]]></description>
   </item>
   <item>
      <title>controlP5 Toggle button</title>
      <link>https://forum.processing.org/two/discussion/6490/controlp5-toggle-button</link>
      <pubDate>Fri, 25 Jul 2014 01:30:35 +0000</pubDate>
      <dc:creator>philspitler</dc:creator>
      <guid isPermaLink="false">6490@/two/discussions</guid>
      <description><![CDATA[<p>Hi, I have 10 buttons in a UI and it all works great, the issue I have is that I want the active button to remain highlighted</p>

<p>I added the  .setSwitch(true) to each button which acts like a toggle but the issues that when I click another button, the first button still stay highlighted.</p>

<p>How can I have a selected state?</p>

<p>Any idea?</p>

<p>Thanks.</p>

<p>Phil</p>
]]></description>
   </item>
   <item>
      <title>Why doesn't disconnect TCP client Android from TCP server PC?</title>
      <link>https://forum.processing.org/two/discussion/18506/why-doesn-t-disconnect-tcp-client-android-from-tcp-server-pc</link>
      <pubDate>Tue, 11 Oct 2016 19:19:31 +0000</pubDate>
      <dc:creator>SeUlPiERzMeArN</dc:creator>
      <guid isPermaLink="false">18506@/two/discussions</guid>
      <description><![CDATA[<p>This is my code:</p>

<p>import controlP5.*;
import oscP5.*;
import netP5.*;</p>

<p>/********************************************************************************/
ControlP5 cp5;
controlP5.Button BCONECTAR, BDESCONECTAR;
/********************************************************************************/</p>

<p>/********************************************************************************/
OscP5 oscP5tcpClient;
NetAddress myServerAddress;
/********************************************************************************/</p>

<p>PFont myFont;</p>

<p>/********************************************************************************/
int myColor = color(255), c1, c2;
float n,n1;
boolean INICIO=true;
/********************************************************************************/</p>

<p>/********************************************************************************/
void setup() {
  size(540,960);
  noStroke();</p>

<p>myFont = createFont("Georgia", 32);</p>

<p>cp5 = new ControlP5(this);
/********************************************************************************/
  BCONECTAR = cp5.addButton("CONECTAR")
                 .setValue(0)
                 .setPosition(100,100)
                 .setSize(180,75)
                 ;</p>

<p>BCONECTAR.captionLabel()
           .setSize(50)
           .setFont(myFont)
           .toUpperCase(false)
           .setText("CONECTAR")
           ;</p>

<p>BCONECTAR.getCaptionLabel().align(ControlP5.CENTER, ControlP5.CENTER);<br />
/********************************************************************************/</p>

<p>BDESCONECTAR = cp5.addButton("DESCONECTAR")
                    .setValue(1)
                    .setPosition(100,195)
                    .setSize(240,75)
                    ;</p>

<p>BDESCONECTAR.captionLabel()
              .setSize(50)
              .setFont(myFont)
              .toUpperCase(false)
              .setText("DESCONECTAR")
              ;</p>

<p>BDESCONECTAR.getCaptionLabel().align(ControlP5.CENTER, ControlP5.CENTER);<br />
/********************************************************************************/
}
/********************************************************************************/</p>

<p>/********************************************************************************/
void draw() {
  background(myColor);
  myColor = lerpColor(c1,c2,n);
  n += (1-n)* 0.1; 
}
/********************************************************************************/</p>

<p>/********************************************************************************/
public void CONECTAR(int theValue) {
  println("CONECTAR: " + theValue);
  c1 = c2;
  c2 = color(0,160,100);<br />
  if(INICIO==false)
    {
      oscP5tcpClient = new OscP5(this, "192.168.1.97", 5000, OscP5.TCP);
      myServerAddress = new NetAddress("192.168.1.97", 5000);
    }<br />
}</p>

<p>public void DESCONECTAR(int theValue) {
  println("DESCONECTAR: " + theValue);
  c1 = c2;
  c2 = color(150,0,0);
  if(INICIO==false)
    {
      oscP5tcpClient.stop();
      oscP5tcpClient.dispose();<br />
      oscP5tcpClient.disconnect(myServerAddress);
    }<br />
  INICIO=false;<br />
}
/********************************************************************************/</p>

<p>When I push the button DESCONECTAR the server still says Connected.</p>

<p>Could you please show me the right way to close TCP client?</p>
]]></description>
   </item>
   <item>
      <title>Hello. How to draw a button?</title>
      <link>https://forum.processing.org/two/discussion/17842/hello-how-to-draw-a-button</link>
      <pubDate>Sun, 14 Aug 2016 18:36:48 +0000</pubDate>
      <dc:creator>Gismas</dc:creator>
      <guid isPermaLink="false">17842@/two/discussions</guid>
      <description><![CDATA[<p><img src="https://forum.processing.org/two/uploads/imageupload/502/YCE8CZA5RW6Q.png" alt="Screenshot_2016-08-14-21-16-13" title="Screenshot_2016-08-14-21-16-13" /></p>

<pre><code>import controlP5.*;
ControlP5 cp5;

Object sun;
Object earth;
Object moon;

PVector camPos;
PVector camEye;
float camRadius, camTheta, camPhi;

void setup()
{
    size(displayWidth, displayHeight, P3D);
    cp5 = new ControlP5(this);
    cp5.setAutoDraw(false);
    cp5.addButton("Button",1,20,20,100,20);

    earth = new Object(1000, 0, 0, 100);
    moon = new Object(1200, 0, 0, 20);

    camPos = new PVector(300, 0, 20);
    camEye = new PVector(0, 0, 0);
    camRadius = 2000;
    camTheta = 160;
    camPhi = -40;
}

void draw()
{
    background(100, 100, 100);
    camera(camPos.x, camPos.y, camPos.z, camEye.x, camEye.y, camEye.z, 0, 0, 1);
    noLights();
    pointLight(255, 255, 255, 150, 0, 0);

    if(mousePressed)
    {
        camTheta += (mouseX - pmouseX);
        camPhi += (pmouseY - mouseY);
    }
    updateCamera();
    earth.draw();
    moon.draw();
}

void updateCamera()
{
    camPos.x = camEye.x + camRadius * cos(camPhi * PI/180) * sin(camTheta * PI/180);
    camPos.y = camEye.y + camRadius * cos(camPhi * PI/180) * cos(camTheta * PI/180);
    camPos.z = camEye.z + camRadius * sin(camPhi * PI/180);
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>using .setSize() with controlP5 imageButtons</title>
      <link>https://forum.processing.org/two/discussion/17848/using-setsize-with-controlp5-imagebuttons</link>
      <pubDate>Mon, 15 Aug 2016 07:53:00 +0000</pubDate>
      <dc:creator>deano</dc:creator>
      <guid isPermaLink="false">17848@/two/discussions</guid>
      <description><![CDATA[<p>Hi there guys, here is the default example for imageButton with ControlP5. (one can find it under Examples)</p>

<p>I was wondering if there was a way to scale up/down say the rolloverImage by a few pixels. So that when you rollover with your mouse the button appears to pop in place.</p>

<p>I tried .setSize(int,int) before .updateSize(); but it does nothing. If you remove the line .updateSize() it freezes.</p>

<p>Any ideas? Tried the java docs but unsure of the syntax/method here.</p>

<pre><code>import controlP5.*;

ControlP5 cp5;

int myColor = color(0);


void setup() {
  size(400, 600);
  cp5 = new ControlP5(this);

  // replace the default controlP5 button with an image.
  // button.setImages(defaultImage, rolloverImage, pressedImage);
  // use button.updateSize() to adjust the size of the button and 
  // resize to the dimensions of the defaultImage

  cp5.addButton("buttonA")
    .setPosition(175, 275)
      .setImages(loadImage("Arrow-Left.png"), loadImage("Arrow-Right.png"), loadImage("Refresh.png"))
        .updateSize();
}

void draw() {
  background(myColor);
}

public void controlEvent(ControlEvent theEvent) {
  println(theEvent.getController().getName());
}

// function buttonA will receive changes from 
// controller with name buttonA
public void buttonA(int theValue) {
  println("a button event from buttonA: "+theValue);
  myColor = color(128);
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>How can I use selectInput() in draw()?</title>
      <link>https://forum.processing.org/two/discussion/16502/how-can-i-use-selectinput-in-draw</link>
      <pubDate>Mon, 09 May 2016 05:57:45 +0000</pubDate>
      <dc:creator>Program12321</dc:creator>
      <guid isPermaLink="false">16502@/two/discussions</guid>
      <description><![CDATA[<p>Hi, I'm trying to open the File Selection window with a controlp5 button in draw() and choose an image. When I choose my image and I open it double-clicking the image, it appears in the program normally, but when I select the image and press "Open" or "Cancel" int he File Selection window, another window of selection appears again and again. Please I need help  :/</p>

<p>Here is my code:</p>

<p>`
import controlP5.*;</p>

<p>ControlP5 cp5;</p>

<p>PImage image;
String file,pass;</p>

<p>void setup(){
  size(1300,720);</p>

<p>cp5 = new ControlP5(this);</p>

<p>cp5.addButton("Open")
     .setValue(0)
     .setPosition(1000,100)
     .setSize(70,30)
     ;
}</p>

<p>void draw(){</p>

<p>if (cp5.get(Button.class, "Open").isPressed()){
    pass = "open";
    file = "none";
    selectInput("Select a file to process:", "fileSelected");
    interrupt();
    if (file != null &amp;&amp; file != "nothing"){
      image = loadImage(file);
   }
   else{
     image = createImage(850,650,RGB);
    for (int i = 0; i &lt; image.pixels.length; i++) {
      image.pixels[i] = color(0, 0, 0); 
    } 
    image.updatePixels();</p>

<p>}</p>

<p>}</p>

<p>if (pass == "open"){</p>

<p>image(image,0,0,800,600);</p>

<p>}</p>

<p>}</p>

<p>void fileSelected(File selection) {
  if (selection == null) {
    //println("Window was closed or the user hit cancel.");
    file = "nothing";
  } else {
    //println("User selected " + selection.getAbsolutePath());
    file = selection.getAbsolutePath();
}
}</p>

<p>void interrupt() {
  while(file == "none") {
    noLoop();
  }
  loop();
}
`</p>
]]></description>
   </item>
   <item>
      <title>two buttons in the same place that act like a switch.</title>
      <link>https://forum.processing.org/two/discussion/15054/two-buttons-in-the-same-place-that-act-like-a-switch</link>
      <pubDate>Mon, 22 Feb 2016 08:20:12 +0000</pubDate>
      <dc:creator>vangalvin</dc:creator>
      <guid isPermaLink="false">15054@/two/discussions</guid>
      <description><![CDATA[<p>I am trying to build a login interface for an arduino that has several sensors, I was trying to create a button that would allow me to record and log to file and when clicked the button would become hidden run the associated code then the STOP button would become visible. Once that is clicked the logging would stop, hide the button and bring the REC button to the front.</p>

<p>The code kind of works but I am getting a bunch of errors.
Here is a copy of what I have so far.</p>

<pre>`
import controlP5.*;
import java.util.*;


ControlP5 cp5;

Chart myChart1;
Chart myChart2;
Chart myChart3;
Chart myChart4;

Button b1;
Button b2;

Textlabel b1Lbl;
boolean logging = false;
String bevent;

void setup() {
  size(800, 600);
  cp5 = new ControlP5(this);
  
  List l = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h");
  /* add a ScrollableList, by default it behaves like a DropdownList */
  cp5.addScrollableList("SELECT COM PORT")
     .setPosition(10, 10)
     .setSize(200, 100)
     .setBarHeight(20)
     .setItemHeight(20)
     .addItems(l)
     .close()
     // .setType(ScrollableList.LIST) // currently supported DROPDOWN and LIST
     ;
  // create a new button with name 'REC'
  b1 = cp5.addButton("REC")
     .setValue(0)
     .setPosition(740,10)
     .setSize(50,20)
//     .setLabel("REC")
     .setVisible(true)
     ;
     
  b2 = cp5.addButton("STOP")
     .setValue(0)
     .setPosition(740,10)
     .setSize(50,20)
//     .setLabel("STOP")
     .setVisible(false)
     ;
     
  myChart1 = cp5.addChart("sensor1")
     .setPosition(10, 40)
     .setSize(385, 200)
     .setRange(-10, 120)
     .setView(Chart.LINE) // use Chart.LINE, Chart.PIE, Chart.AREA, Chart.BAR_CENTERED
     .setStrokeWeight(1.5)
     .setColorCaptionLabel(color(40))
     .setLabel("")
     ;

//  myChart1.addDataSet("sensin1");
//  myChart1.setData("sensein1", new float[100]);

  myChart2 = cp5.addChart("sensor2")
     .setPosition(405, 40)
     .setSize(385, 200)
     .setRange(-10, 120)
     .setView(Chart.LINE) // use Chart.LINE, Chart.PIE, Chart.AREA, Chart.BAR_CENTERED
     .setStrokeWeight(1.5)
     .setColorCaptionLabel(color(40))
     .setLabel("")
     ;

//  myChart2.addDataSet("sensin2");
//  myChart2.setData("sensin2", new float[100]);

  myChart3 = cp5.addChart("sensor3")
     .setPosition(10, 250)
     .setSize(385, 200)
     .setRange(-10, 120)
     .setView(Chart.LINE) // use Chart.LINE, Chart.PIE, Chart.AREA, Chart.BAR_CENTERED
     .setStrokeWeight(1.5)
     .setColorCaptionLabel(color(40))
     .setLabel("")
     ;

//  myChart3.addDataSet("sensin3");
//  myChart3.setData("sensein3", new float[100]);

  myChart4 = cp5.addChart("sensor4")
     .setPosition(405, 250)
     .setSize(385, 200)
     .setRange(-10, 120)
     .setView(Chart.LINE) // use Chart.LINE, Chart.PIE, Chart.AREA, Chart.BAR_CENTERED
     .setStrokeWeight(1.5)
     .setColorCaptionLabel(color(40))
     .setLabel("")
     ;

//  myChart4.addDataSet("sensin4");
//  myChart4.setData("sensin4", new float[100]);
}

void draw() {
  background(240);
}

public void REC(){
  b1.hide();
  b2.show();
  b2.bringToFront();
  logging = true;
  println("Logging Data to File");
}

public void STOP(){
  b2.hide();
  b1.show();
  b1.bringToFront();
  logging = false;
  println("Stop Logging Data");
}

void dropdown(int n) {
  /* request the selected item based on index n */
  println(n, cp5.get(ScrollableList.class, "dropdown").getItem(n));
  
  /* here an item is stored as a Map  with the following key-value pairs:
   * name, the given name of the item
   * text, the given text of the item by default the same as name
   * value, the given value of the item, can be changed by using .getItem(n).put("value", "abc"); a value here is of type Object therefore can be anything
   * color, the given color of the item, how to change, see below
   * view, a customizable view, is of type CDrawable 
   */
  
   CColor c = new CColor();
  c.setBackground(color(255,0,0));
  cp5.get(ScrollableList.class, "dropdown").getItem(n).put("color", c);
  
}

void keyPressed() {
  switch(key) {
    case('1'):
    /* make the ScrollableList behave like a ListBox */
    cp5.get(ScrollableList.class, "dropdown").setType(ControlP5.LIST);
    break;
    case('2'):
    /* make the ScrollableList behave like a DropdownList */
    cp5.get(ScrollableList.class, "dropdown").setType(ControlP5.DROPDOWN);
    break;
    case('3'):
    /*change content of the ScrollableList */
    List l = Arrays.asList("a-1", "b-1", "c-1", "d-1", "e-1", "f-1", "g-1", "h-1", "i-1", "j-1", "k-1");
    cp5.get(ScrollableList.class, "dropdown").setItems(l);
    break;
    case('4'):
    /* remove an item from the ScrollableList */
    cp5.get(ScrollableList.class, "dropdown").removeItem("k-1");
    break;
    case('5'):
    /* clear the ScrollableList */
    cp5.get(ScrollableList.class, "dropdown").clear();
    break;
  }
}`
</pre>

<p>The errors I am getting are as follows...</p>

<pre>
Feb 22, 2016 9:16:32 PM controlP5.ControlBroadcaster printMethodError
SEVERE: An error occured while forwarding a Controller event, please check your code at REC
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at controlP5.ControlBroadcaster.invokeMethod(Unknown Source)
    at controlP5.ControlBroadcaster.callTarget(Unknown Source)
    at controlP5.ControlBroadcaster.broadcast(Unknown Source)
    at controlP5.Controller.broadcast(Unknown Source)
    at controlP5.Button.setValue(Unknown Source)
    at TemperatureGUI_001.setup(TemperatureGUI_001.java:67)
    at processing.core.PApplet.handleDraw(PApplet.java:2377)
    at processing.awt.PSurfaceAWT$12.callDraw(PSurfaceAWT.java:1527)
    at processing.core.PSurfaceNone$AnimationThread.run(PSurfaceNone.java:316)
Caused by: java.lang.NullPointerException
    at TemperatureGUI_001.REC(TemperatureGUI_001.java:140)
    ... 13 more
Feb 22, 2016 9:16:32 PM controlP5.ControlBroadcaster printMethodError
SEVERE: An error occured while forwarding a Controller event, please check your code at STOP
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at controlP5.ControlBroadcaster.invokeMethod(Unknown Source)
    at controlP5.ControlBroadcaster.callTarget(Unknown Source)
    at controlP5.ControlBroadcaster.broadcast(Unknown Source)
    at controlP5.Controller.broadcast(Unknown Source)
    at controlP5.Button.setValue(Unknown Source)
    at TemperatureGUI_001.setup(TemperatureGUI_001.java:75)
    at processing.core.PApplet.handleDraw(PApplet.java:2377)
    at processing.awt.PSurfaceAWT$12.callDraw(PSurfaceAWT.java:1527)
    at processing.core.PSurfaceNone$AnimationThread.run(PSurfaceNone.java:316)
Caused by: java.lang.NullPointerException
    at TemperatureGUI_001.STOP(TemperatureGUI_001.java:148)
    ... 13 more
</pre>

<p>The unusual thing is that the code actually seems to work and the button acts the way I would have expected it but would rather not have the errors.</p>
]]></description>
   </item>
   <item>
      <title>ControlP5 button event triggered on load</title>
      <link>https://forum.processing.org/two/discussion/14850/controlp5-button-event-triggered-on-load</link>
      <pubDate>Wed, 10 Feb 2016 21:02:44 +0000</pubDate>
      <dc:creator>asimkumar</dc:creator>
      <guid isPermaLink="false">14850@/two/discussions</guid>
      <description><![CDATA[<p>examples/controllers/ControlP5button/ControlP5button.pde
the example program for button, this triggers event on screen start,  removing the value property makes it start without any event trigger, how can i start button with value without trigger.</p>
]]></description>
   </item>
   <item>
      <title>Problem with saving picture to sdcard (empty picture).</title>
      <link>https://forum.processing.org/two/discussion/14376/problem-with-saving-picture-to-sdcard-empty-picture</link>
      <pubDate>Sun, 10 Jan 2016 17:52:12 +0000</pubDate>
      <dc:creator>Biter</dc:creator>
      <guid isPermaLink="false">14376@/two/discussions</guid>
      <description><![CDATA[<p>Hello,
I am trying to save a picture (save() or saveFrame() to Sdcard. The file is empty. 
Everything works fine in Java mode.</p>

<p>I have enabled the permission - WRITE_EXTERNAL_STORAGE
I can save .txt file but problem is with pictures. The file has 0kB size.</p>

<p>Here's my simply code.</p>

<pre><code>import controlP5.*;

ControlP5 cp5;
PImage backgroundImg = null;

void setup() 
{
  size(displayWidth, displayHeight);
  backgroundImg = loadImage("backImg.jpg");
  backgroundImg.resize(width, height);
  backgroundImg.loadPixels();

  cp5 = new ControlP5(this);
  cp5.addButton("savePicBut")
  .setBroadcast(false)
  .setPosition(30, 30)
  .setSize(30,30)
  .setLabel("Save")
  .setBroadcast(true);
}

void draw() 
{ 
    background(backgroundImg);
}

public void savePicBut()
{
  saveFrame("//sdcard/PicTest.png");

  String[] words = {"test1","test2","test3"};
  saveStrings("//sdcard/words.txt",words);  
}
</code></pre>

<p>Thanks a lot for your help. 
Sebastian</p>
]]></description>
   </item>
   <item>
      <title>controlP5 - get value when pressing a button</title>
      <link>https://forum.processing.org/two/discussion/14176/controlp5-get-value-when-pressing-a-button</link>
      <pubDate>Tue, 29 Dec 2015 00:49:21 +0000</pubDate>
      <dc:creator>Per</dc:creator>
      <guid isPermaLink="false">14176@/two/discussions</guid>
      <description><![CDATA[<p>I want to get the value from the button when I press the button (but without using a function). Got two alternatives but none of them are good (most be a better way then using the <strong>if (mousePressed)</strong>. How can I succed with this probably simple task. Guess i want to use some of these but I cant figure out how to implement them:</p>

<blockquote class="Quote">
  <p>controlP5.Button : boolean isPressed() <br />
  controlP5.Controller : boolean isMousePressed() <br />
  controlP5.Controller : Button onPress(CallbackListener)</p>
</blockquote>

<p>Anyone can guide me getting value from button without using function?</p>

<pre><code>import controlP5.*;

ControlP5 cp5;

void setup() {
  size(400, 600);

  cp5 = new ControlP5(this);

  cp5.addButton("Button")
    .setValue(1)
    .setPosition(100, 100)
    .setSize(200, 19)
    ;
}

void draw() {
  background(255);

  if (mousePressed) {
    // alternative 1
    println("\nalternative 1: " + cp5.getController("Button").getValue());

    // alternative 2
    println("alternative 2: " + cp5.isMouseOver(cp5.getController("Button")));
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Add / remove button</title>
      <link>https://forum.processing.org/two/discussion/14154/add-remove-button</link>
      <pubDate>Sat, 26 Dec 2015 14:03:54 +0000</pubDate>
      <dc:creator>Per</dc:creator>
      <guid isPermaLink="false">14154@/two/discussions</guid>
      <description><![CDATA[<p>Ive created the following example for adding buttons with "<strong>+</strong>" and removing buttons with "<strong>-</strong>". But I cant find out how to remove a button. Only adding. It would be perfect if something like <strong>removeButton()</strong> existed but it doesnt so need another solution. Any suggestion is very much apreciated!</p>

<pre><code>import controlP5.*;
ControlP5 cp5;

int listNr = 0;
StringList list;

void setup() {
  size(400, 600);
  cp5 = new ControlP5(this);

  list = new StringList(); 
  list.append(str(listNr));

  cp5.addButton("listNumber: " + listNr)
    .setValue(0) // detta värde skickas när den trycks ner
    .setPosition(100, 100+(listNr*30))
    .setSize(200, 19)
    ;
}

void draw() {
}

void keyReleased() {
  if (key == '+') {
    listNr++;
  } else if (key == '-') {
    listNr--;
  }

  // if the button doesnt exist - add a new one
  for (int i = 0; i &lt; list.size(); i++) {
    if (listNr == list.size()-1) {
      println("DO NOTHING");
      break; // leave loop
    } else if (listNr &gt; list.size()-1) {
      println("ADD BUTTON");
      cp5.addButton("listNumber: " + listNr)
        .setValue(0) 
        .setPosition(100, 100+(listNr*30))
        .setSize(200, 19)
        ;
      list.append(str(listNr));
      break; // leave loop
    } else if (listNr &lt; list.size()-1) {
      println("REMOVE BUTTON");

      /* HERE I WANT TO DO SIMILIAR THING AS ABOVE BUT REMOVE A BUTTON
       cp5.removeButton("listNumber: " + listNr); // BUT THIS DOESNT WORK
       */

      list.remove(listNr);
      break; // leave loop
    }
  }

  println("listNr: " + listNr + " LISTSIZE: " + list.size());
  println("LIST: " + list);
  println("====================");
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>How to invoke resize(int,int) on a array type PImage()</title>
      <link>https://forum.processing.org/two/discussion/13496/how-to-invoke-resize-int-int-on-a-array-type-pimage</link>
      <pubDate>Thu, 12 Nov 2015 15:43:58 +0000</pubDate>
      <dc:creator>mmuylle</dc:creator>
      <guid isPermaLink="false">13496@/two/discussions</guid>
      <description><![CDATA[<p>This is needed to adapt the graphics to the different sizes of my android devices.</p>

<pre><code>import controlP5.*;
int buttonSize = ... ;
ControlP5 MyController;
Button but_Play;
MyController = new ControlP5(this);

  // make button Play

  PImage[] play_Img = {loadImage("play.png"), loadImage("play.png"), loadImage("play.png")};

  //**play_Img.resize(0,60); = not allowed**

  but_Play = MyController.addButton("but_Play")
    .setValue(0)
    .setPosition(tab, dotWidth)
    .setSize(buttonSize, buttonSize)
    .setImages(play_Img)
    .updateSize()
    ;
</code></pre>
]]></description>
   </item>
   <item>
      <title>ControlP5 Button Functions Always Firing</title>
      <link>https://forum.processing.org/two/discussion/13361/controlp5-button-functions-always-firing</link>
      <pubDate>Mon, 02 Nov 2015 14:27:02 +0000</pubDate>
      <dc:creator>bkraynor</dc:creator>
      <guid isPermaLink="false">13361@/two/discussions</guid>
      <description><![CDATA[<p>I've seen that some other users have had issues with the controlP5 button controllers firing on app launch. My controller seems to be firing all the time, even if I use a flag to prevent the function from running on the first call. Here's my code:</p>

<pre>
void draw_start_screen() {
  cp5 = new ControlP5(this);
  
  cp5.addButton("buttonA")
     .setValue(0)
     .setPosition(W/2,H/2)
     .setSize(100,100);
}

void buttonA(int theValue) { 
  if (firstLoop) { 
    firstLoop = false;
  }
  
  println(theValue);
}

</pre>

<p>When I run my app, it continuously prints 0 to the console. Does anyone have a solution to this issue?</p>
]]></description>
   </item>
   <item>
      <title>Error to close the window with ControlP5</title>
      <link>https://forum.processing.org/two/discussion/13312/error-to-close-the-window-with-controlp5</link>
      <pubDate>Thu, 29 Oct 2015 16:47:20 +0000</pubDate>
      <dc:creator>Jose_Aparecido</dc:creator>
      <guid isPermaLink="false">13312@/two/discussions</guid>
      <description><![CDATA[<p>Hello guys,</p>

<p>I open two windows using the buttons have controlP5 library, the first is a menu where calls this second window ...
I created a button in second window, instead of typing ESC, the same can press in the button to close the window.
When pressed the keys ESC, this code works normal, that is, closes the window and returns to the menu normally.
But however when chamos the same function as used in the ESC, with the button,  the following error occurs:</p>

<pre><code>java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 4
    at java.util.Vector.get(Unknown Source)
    at controlP5.ControllerList.get(Unknown Source)
    at controlP5.ControllerGroup.setMousePressed(Unknown Source)
    at controlP5.ControlWindow.mouseReleasedEvent(Unknown Source)
    at controlP5.ControlWindow.mouseEvent(Unknown Source)
    at sun.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at processing.core.PApplet$RegisteredMethods.handle(PApplet.java:1236)
    at processing.core.PApplet.handleMethods(PApplet.java:1431)
    at processing.core.PApplet.handleMouseEvent(PApplet.java:2826)
    at processing.core.PApplet.dequeueEvents(PApplet.java:2725)
    at processing.core.PApplet.handleDraw(PApplet.java:2397)
    at processing.core.PGraphicsJava2D.requestDraw(PGraphicsJava2D.java:240)
    at processing.core.PApplet.run(PApplet.java:2256)
    at java.lang.Thread.run(Unknown Source)
</code></pre>

<p>The second window was closed, but an error occurs in the first window, as if he could no longer run something ...
Any idea how to solve this?</p>

<p>Note: I will leave part of the code below, but it will not work, because it is only a part.</p>

<p>First Window ( Menu )</p>

<pre><code>static class Video02 extends PApplet {
  atualizaVar atualizaVarVideo02 = new atualizaVar(0,0);
  ControlP5 cp5_Video02; 

  int savedTimeVideo02, totalTimeVideo02 = 5000;
  float pontoAtuVideo02 = 0,
  int bar_sizeVideo02   = 15;
  int contBtn02         = 0;
  int menu02            = 1;
  int qtdeMenus02       = 1;
  int menuAtivo02       = 1;

  PVector v1_Video02;
  String[][] botoesMenu02;

  XML xml_Video02; //Variável para carregar arquivo XML
  ArrayList targetsVideo02 = new ArrayList();

  boolean retornaMenu = false;

  //Configurações Iniciais
  void setup(){
    size(displayWidth, displayHeight, JAVA2D); //Define tamanho da Janela, e forma de renderização
    background(255);             //Limpa tela
    smooth();                    //Suaviza serrilhado nos contornos do desenho
    textFont(utilVar.fontA, 40); //Define e de fonte e Tamanho
    fill(#1273C1);               //Seta cor para o Texto

    cp5_Video02 = new ControlP5(this); //Instancia objeto ControlP5 ( Biblioteca Gráfica )
    criaObjetosVideo02();

    utilVar.tempoAutClick = true;
    savedTimeVideo02      = millis();
    v1_Video02            = new PVector(0, 0);
    rob.mouseMove(30, height-100);

    cursor(HAND);
  }

  //Loop enquanto rodar o programa
  void draw(){

    background(255);
    textFont(utilVar.fontA, 40);
    fill(#1273C1);
    text("Escolha uma Opção para selecionar o Vídeo...", 70, 40);

    if (utilVar.tempoAutClick &amp;&amp; focused){
      if (Collections.disjoint(cp5_Video02.getMouseOverList(), targetsVideo02)==false) {
        if(cp5_Video02.getMouseOverList().size()==1) {
          controlP5.Controller controllerVideo02 = (controlP5.Controller)(cp5_Video02.getMouseOverList().get(0));

          String posicoes = controllerVideo02.getLabel().toString();
          String posBtnX  = posicoes.substring(0,4); 
          String posBtnY  = posicoes.substring(5,posicoes.length());

          desenhaBarraVideo02(int(posBtnX)-17, int(posBtnY)+150, 5, 150);
        }
      } else {
        savedTimeVideo02 = millis();
        pontoAtuVideo02  = 0;
      }
    } else {
      savedTimeVideo02 = millis();
      pontoAtuVideo02  = 0;
    }

    if (!utilVar.executando3 &amp;&amp; utilVar.usaLeapMotion){
      atualizaVarVideo02.atualizaLeap(utilVar.opcaoLeapMotion);
      rob.mouseMove(atualizaVarVideo02.xPos, atualizaVarVideo02.yPos);
    } else {
      atualizaVarVideo02.xPos = mouseX;
      atualizaVarVideo02.yPos = mouseY;
    }  
  }

  void mouseMoved(){   

  }

  void mousePressed(){
    utilVar.pressMouse3 = true;
  }

  void keyPressed() {
    if ( key == ESC ){
      retornaMenu();
      desabilitaDisp();
    }
 }

  void retornaMenu(){
    key = 0;
    this.stop();
    this.dispose();
    frame.hide();
    frame                = null;
    cp5_Video02          = null;
    atualizaVarVideo02   = null;
    utilVar.pressMouse3  = false;
    utilVar.executando2  = false;
    desabilitaDisp();
  }

  void desenhaBarraVideo02(int pW, int pH, int perc, int pontoMax){
    color c = color(0, 126, 255, 150);

    if (pontoAtuVideo02 &lt; pontoMax){
      pontoAtuVideo02 = pontoAtuVideo02 + utilVar.tempoAutClickMouse; //Conforme calibrar variával ( tempoAutClickMouse ), muda o tempo do Click automático
      fill (c);
      rect(pW, pH, bar_sizeVideo02, pontoAtuVideo02*-1 );
    } else { 
      pontoAtuVideo02 = 0;
      cliCkMouse();
      utilVar.pressMouse2 = true;
    }
  }

  void controlEvent(ControlEvent theControlEvent) {
    if (utilVar.pressMouse3){
      utilVar.opcaoLink = int(theControlEvent.controller().getValue());
      String nomeBotaoVideo02  = theControlEvent.controller().getName(); 

      if (nomeBotaoVideo02 == "btnProximoVideo02" || nomeBotaoVideo02 == "btnAnteriorVideo02" || nomeBotaoVideo02 == "btnVoltarVideo02"){
        if (nomeBotaoVideo02 == "btnProximoVideo02"){
          if (menuAtivo02 &lt; menu02){ 
            menuAtivo02++;
            habilitaDesabilitaMenu02(menuAtivo02);
          }  
        } else if (nomeBotaoVideo02 == "btnAnteriorVideo02"){
          if (menuAtivo02 &gt; 1){ 
            menuAtivo02--;
            habilitaDesabilitaMenu02(menuAtivo02);
          }
        } else if (nomeBotaoVideo02 == "btnVoltarVideo02"){ //Here is Called Idem press key ESC
          println("Volta 1");
          key = ESC;
          retornaMenu();
        } 
      } else {
        utilVar.imgPai      = int(theControlEvent.controller().getStringValue());
        utilVar.executando3 = true;    

        PApplet video03 = new Video03();  
        runSketch(new String[] { "***Vídeos***" }, video03);
      }  
    }
  }

  void criaObjetosVideo02(){
    xml_Video02 = loadXML(PATHIMGMENUVIDEOS + "/" + utilVar.idPessoa +"/pessoasMenuVideos.xml");
    XML[] children = xml_Video02.getChildren("menuVideo");

    botoesMenu02  = new String[children.length][2];

    for (int i = 0; i &lt; children.length; i++) {
      int idButton    = children[i].getInt("id");
      String idImagem = children[i].getString("id");
      int opcLink     = children[i].getInt("opcaoLink"); 
      String urlLink  = children[i].getString("linkURL");

      contBtn02++;    
      adicionaPosBtnXY(i, opcLink, contBtn02);
      //println("Path " + PATHIMGMENUVIDEOS + "/" + idPessoa + "/" + idImagem);
      cp5_Video02.addButton("btn"+nf(idButton,6))
                 .setId(idButton)
                 .setPosition(utilVar.posBtnX, utilVar.posBtnY)
                 .setImages(loadImage(PATHIMGMENUVIDEOS+"/"+utilVar.idPessoa+"/"+idImagem+"_0.jpg"), loadImage(PATHIMGMENUVIDEOS+"/"+utilVar.idPessoa+"/"+idImagem+"_1.jpg"), loadImage(PATHIMGMENUVIDEOS+"/"+utilVar.idPessoa+"/"+idImagem+"_2.jpg"))
                 .setStringValue(idImagem)
                 .setValue(opcLink)
                 .setLabel(nf(utilVar.posBtnX,4) + "," + nf(utilVar.posBtnY,4))
                 .setVisible(false)
                 .updateSize();

      targetsVideo02.add(cp5_Video02.getController("btn"+nf(idButton,6)));

      botoesMenu02[i][0] = "btn"+nf(idButton,6);
      botoesMenu02[i][1] = Integer.toString(menu02);

    }//for

    cp5_Video02.addButton("btnVoltarVideo02")
               .setPosition(2, 2)
               .setImages(loadImage(PATHDADOS + "/voltar0.png"), loadImage(PATHDADOS + "/voltar1.png"), loadImage(PATHDADOS + "/voltar2.png"))
               .updateSize();

    targetsVideo02.add(cp5_Video02.getController("btnVoltarVideo02"));

    habilitaDesabilitaMenu02(1);
  }

  void habilitaDesabilitaMenu02(int opcaoMnu){
    for (int i = 0; i &lt; botoesMenu02.length; i++) {
      cp5_Video02.getController(botoesMenu02[i][0]).setVisible((int(botoesMenu02[i][1]) == opcaoMnu));
    }
  }
}//função 
</code></pre>

<p>Only code execute on exit second window</p>

<pre><code>public static final class Video03 extends PApplet {
...

void keyPressed() {
    if ( key == ESC ){
      retornaMenu();
      desabilitaDisp();
    }
}

void controlEvent(ControlEvent theControlEvent) {
    if (utilVar.pressMouse3){
      String nomeBotao03  = theControlEvent.controller().getName(); 
      if (nomeBotao03 == "btnVoltarVideo03"){
        key = ESC;
        retornaMenu();
      }
    }

void retornaMenu(){
    //if (key == ESC ){
      key = 0;
      this.stop();
      this.dispose();
      frame.hide();
      frame               = null;
      //cp5_Video03         = null;
      atualizaVarVideo03  = null;
      utilVar.pressMouse2 = false;
      utilVar.pressMouse3 = false;
      utilVar.executando3 = false;
      desabilitaDisp();
    //}
  }
</code></pre>

<p>Summing up, the function retornaMenu() works on the ESC key, but not when triggered by controlP5, generating the error.
I hope I have managed to explain ...</p>

<p>Thanks for listening.</p>
]]></description>
   </item>
   </channel>
</rss>