Help with ControlP5

Hello guys,

As would extract only the code for the numeric part (after the first and before the second colhete), and the number can vary from 1 to 6 digits for example?

I am using this function:

String nomeBotao = cp5_04.window(this).getMouseOverList(); 
println(nomeBotao);

The reason you need this is that I may control in a single event, several buttons without worrying about the name of each ...

example:

if (cp5_04.isMouseOver(cp5_04.getController("btn1"))){
  if (tempoAutClick) verificaTempo();
} else if (cp5_04.isMouseOver(cp5_04.getController("btn2"))){
   if (tempoAutClick) verificaTempo();
} else {
  clicouMouse = false;
  savedTime   = millis();
}

Would look like this:

 if (cp5_04.isMouseOver(cp5_04.getController(nomeBotao))){
    if (tempoAutClick) verificaTempo();
 } else {
   clicouMouse = false;
   savedTime   = millis();
 }

I hope you understand.

Thank you.

Tagged:

Answers

  • edited September 2015

    Hi, if I understood you correctly you are looking for a way to dynamically check if the mouse is inside a certain controller? If yes, the following example might help? (I am using the latest version of ControlP5, 2.2.5)

    ControlP5 cp5;
    
    void setup() {
      size(400, 400);
      cp5 = new ControlP5(this);
      for (int i=0; i<10; i++) {
        cp5.addButton("button-"+i).setPosition(10, 10+i*30).setSize(200, 20);
      }
    }
    
    
    void draw() {
      background(20);
      String test = "button-1";
      // check if the list returned by cp5.getMouseOverList()
      // contains a controller associated with the name stored 
      // inside variable test.
      if (cp5.getMouseOverList().contains(cp5.getController(test))) {
        println("mouse-over",test, millis());
      } else {
        // no match
      }
    }
    

    if you are looking for a solution that checks if the mouseOverList contains any of many Controllers, then the following example will give you some ideas to work with, please see the comments for further details

    import controlP5.*;
    import java.util.*;
    
    ControlP5 cp5;
    
    
    void setup() {
      size(400, 400);
      cp5 = new ControlP5(this);
      for (int i=0; i<10; i++) {
        cp5.addButton("button-"+i).setPosition(10, 10+i*30).setSize(200, 20);
      }
    }
    
    
    void draw() {
      background(20);
    
      List targets = new ArrayList();
      targets.add(cp5.getController("button-1"));
      targets.add(cp5.getController("button-2"));
    
      // the List 'targets' will contain the controllers we want to 
      // evaluate in the following conditional statement
    
      // check if the mouseOverList and the targets list share some elements
      // the code below makes use of method disjoint from the java.util.Collections
      // class http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html  
      if (Collections.disjoint(cp5.getMouseOverList(), targets)==false) {
      // a match was found, now get the Controller stored 
      // inside the mouseOverList
        if(cp5.getMouseOverList().size()==1) {
          Controller c = (Controller)(cp5.getMouseOverList().get(0));
          println(c.getName());
        }
      } else {
        // no match
      }
    
    }
    
  • Hello Sojamo,

    Thanks for the feedback, and sorry for my English, I write with the help of Google Translate, my native language is Portuguese ...

    You understand perfectly what I need to do, I'm riding a series of buttons dynamically, and then need to know if the focus is positioned on each, to trigger the "Click" automatically, based on a period to be determined.

    The example you passed think will work well, but would like to try to complete a medium that I'm trying to do, ie I need to capture part of the array, to a string, so I can use as a button name.

    Could you give an example to cut part of the Array for a String, using the tool?

    //String nameButton = cp5_05.window(this).getMouseOverList();

    For example, it would be cut in positions 2 to 9 ...

    You could use substring? But giving type of error in the conversion ...

    Below is the code I'm using, to get an idea (is only a part, because the project is divided into parts "Menus")

    public static final class Animacao05 extends PApplet {
      private ControlP5 cp5_05; //Cria objeto da biblioteca ControlP5
    
      XML xml_05; //Variável para carregar arquilo XML
    
      GImageButton btnCronometro05;
    
    
      //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(fontA, 40); //Define e de fonte e Tamanho
        fill(#1273C1);       //Seta cor para o Texto
    
        cp5_05 = new ControlP5(this); //Instancia objeto ControlP5 ( Biblioteca Gráfica )
        criaObjetos05();
        cursor(HAND);
      }
    
      //Loop enquanto rodar o programa
      void draw(){
        background(255);
        textFont(fontA, 40);
        fill(#1273C1);
        text("Escolha uma Opção para selecionar o Vídeo...", 70, 40);
    
        //String nameButton = cp5_05.window(this).getMouseOverList(); 
        println(cp5_05.window(this).getMouseOverList());
    
        if (tempoAutClick){
          //if ( sobreBotao(nameButton) ) 
          if ( sobreBotao("btn1")  || sobreBotao("btn2") ) //--> Many Buttons here
            verificaTempo();
          else {
            clicouMouse = false;
            savedTime   = millis();
          }
        }
        if (usaDispositivos) validaDispositivos(mouseX, mouseY);
      }
    
      boolean sobreBotao(String botao){
        boolean result = cp5_05.isMouseOver(cp5_05.getController(botao));
        return result;
      } 
    
      void mouseMoved(){   
        //      
      }
    
      void mousePressed(){
        pressMouse2 = true;
      }
    
      void keyPressed() {
        if ( key == ESC ){
          retornaMenu();
          desabilitaDisp();
        }
        validaTeclaPress(key);
      }
    
      void btnVoltar(){
        //key = ESC;
        //retornaMenu();
      }  
      void retornaMenu(){
        if (key == ESC ){
          key = 0;
          this.stop();
          this.dispose();
          frame.hide();
          frame       = null;
          cp5_05      = null;
          pressMouse2 = false;
          desabilitaDisp();
        }
      }
    
      void verificaTempo(){ 
        int passedTime = millis() - savedTime;
        if (passedTime > totalTime) {
          //btn05_01();
          mousePressed();
          clicouMouse = true;     //Controle para somente uma vez, quando está com o foco sobre o mouse 
          savedTime   = millis(); //Salva tempo atual
        }
      }
    
      void criaObjetos05(){
    
        xml_05 = loadXML(PATHIMGMENUVIDEOS + "/" + idPessoa +"/pessoasMenuVideos.xml");
        XML[] children = xml_05.getChildren("menuVideo");
    
        for (int i = 0; i < 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");
    
          adicionaPosBtnXY(i, opcLink);
          //println("Path " + PATHIMGMENUVIDEOS + "/" + idPessoa + "/" + idImagem);
    
          cp5_05.addButton("btn"+nf(idButton,6))
                .setPosition(posBtnX, posBtnY)
                .setImages(loadImage(PATHIMGMENUVIDEOS+"/"+idPessoa+"/"+idImagem+"_0.jpg"), loadImage(PATHIMGMENUVIDEOS+"/"+idPessoa+"/"+idImagem+"_1.jpg"), loadImage(PATHIMGMENUVIDEOS+"/"+idPessoa+"/"+idImagem+"_2.jpg"))
                .setCaptionLabel(urlLink)
                .setValue(opcLink)
                .updateSize();
        }//for
    
        //Botão retornar
        cp5_05.addButton("btnVoltar")
              .setPosition(1, 1)
              .setImages(loadImage(PATHDADOS + "/voltar0.jpg"), loadImage(PATHDADOS + "/voltar1.jpg"), loadImage(PATHDADOS + "/voltar2.jpg"))
              .updateSize();
    
        String[] files;
    
       files            = new String[] {"cronometro.jpg", "cronometro.jpg", "cronometro.jpg"};
       btnCronometro05  = new GImageButton(this, width-120, height-75, files);
       btnCronometro05.setVisible(false);
      }//função
    
      void controlEvent(ControlEvent theControlEvent) {
        if (pressMouse2){
          //println("LInk: " + theControlEvent.controller().getLabel());
          opcaoLink = int(theControlEvent.controller().value());
    
          if (opcaoLink == 1){ //Definido Link para abrir página
            link(theControlEvent.controller().getLabel()); //Change to getStringValue...
          } else { //Escolher entre duas opções para abrir página    
            imgPai = int(theControlEvent.controller().getLabel());
    
            PApplet animacao07 = new Animacao07();  
            runSketch(new String[] { "***Vídeos***" }, animacao07);
          }
        }
      }
    }
    

    Below is an print, passing an idea of how is the project.

    If you can help me solve this detail, I thank you, anyway is another way you went, you should also work.

    Thank youImg07

  • Hello,

    Updated the library, and the second example works perfectly, as expected, now I just need to add as needed in the project.

    Thank you,

  • Hello again,

    Unfortunately, some things have not worked after I updated the library ControlP5, need to review some things to upgrade ...

    As I said before, it could use String as the return of function?

     //String nomeBotao = join(cp5_04.window(this).getMouseOverList(), " "); 
        println(cp5_04.window(this).getMouseOverList());
    

    What is the return type can I use?

    Img08

    In summary, to achieve part of the return cut, ( for example, btn3022 ) can solve the problem.

    If you can give some hint of how to do this would be helpful.

    Thank you,

  • Hello again,

    I could update the Controlp5 library, to resolve other errors that were occurring ...

    Trying to put the code in the Project, gave the error:

    The type Controller is ambiguous

    Error occurs in this line:     C = Controller (Controller) (cp5_05.getMouseOverList () get (0).);

    How do I know who he is in conflict, or rather, how can I solve this?

    Again thank you for your attention.

  • Hi, to answer some questions that were asked above: 1. getMouseOverList() returns a List of Controllers (more specifically Objects that implement the ControllerInterface interface). In most cases the list will contain none or one element (when the mouse is located inside a controller), when Controllers overlap and a mouse inside is detected, the returned list will contain more than 1 elements. To extract the name of an controller, which is of type String, you need to iterate the list and access the name of the Controller with the getName() method:

    for(ControllerInterface c:cp5.getMouseOverList()) {
      println(c.getName());
      if(c.getName().equals("btn3022")) {
        println("hello button btn3022"); 
      }
    }
    
    1. type Controller is ambiguous means there is more than 1 class that uses the Name Controller. If this is the case, you need to specify and add the Controller's package path:

      for(ControllerInterface c:cp5.getMouseOverList()) { controlP5.Controller controller = (controlP5.Controller)(c); println(controller); }

    or controlP5.Controller controller = (controlP5.Controller)(cp5.getMouseOverList().get(0));

    hope that helps

  • Hello,

    Thanks for return again ...

    I managed to recover the button name the other way, through a arrayList for String, but was giving an error when trying to use the name as a string without using "quotes" in the name to make sure it is on the button (IsMouseOver).

    But this otherwise worked well, that's what I needed to do in this case do not even need to know the name of the button, but whether he is about to call the validation time, to do "click" automatic.

    The validation code looked like this:

    Variable before setup

    ArrayList targets = new ArrayList();

    In Setup, call function to create objects

        void criaObjetos05(){
    
            xml_05 = loadXML(PATHIMGMENUVIDEOS + "/" + idPessoa +"/pessoasMenuVideos.xml");
            XML[] children = xml_05.getChildren("menuVideo");
    
            for (int i = 0; i < 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");
    
              adicionaPosBtnXY(i, opcLink);
              //println("Path " + PATHIMGMENUVIDEOS + "/" + idPessoa + "/" + idImagem);
              cp5_05.addButton("btn"+nf(idButton,6))
                    .setPosition(posBtnX, posBtnY)
                    .setImages(loadImage(PATHIMGMENUVIDEOS+"/"+idPessoa+"/"+idImagem+"_0.jpg"), loadImage(PATHIMGMENUVIDEOS+"/"+idPessoa+"/"+idImagem+"_1.jpg"), loadImage(PATHIMGMENUVIDEOS+"/"+idPessoa+"/"+idImagem+"_2.jpg"))
                    .setCaptionLabel(urlLink)
                    .setValue(opcLink)
                    .updateSize();
    
              targets.add(cp5_05.getController("btn"+nf(idButton,6)));
            }//for
    
            //Botão retornar
            cp5_05.addButton("btnVoltar")
                  .setPosition(1, 1)
                  .setImages(loadImage(PATHDADOS + "/voltar0.jpg"), loadImage(PATHDADOS + "/voltar1.jpg"), loadImage(PATHDADOS + "/voltar2.jpg"))
                  .updateSize();
    

    And draw looked like this ...

        if (tempoAutClick){
              if (Collections.disjoint(cp5_05.getMouseOverList(), targets)==false) {
                if(cp5_05.getMouseOverList().size()==1) {
                  controlP5.Controller controller = (controlP5.Controller)(cp5_05.getMouseOverList().get(0));
                  println(controller.getName());
                  verificaTempo();
                }
              }
            } else {
              clickMouse = false;
              savedTime  = millis();
            }
    

    Now continue on with the tests, to perform as expected.

    Thank you very very much,> :)

  • Hello again,

    Another detail, I could "simulate" the click-click on the button?

    For example, have a control that is enabled (tempoAutClick), call a function to check the time elapsed at that point, if exceeded, I call the "Automatic Click" ...

    I tried this way (using mousePressed ()), but is not working.

    In Setup()

    savedTime05 = millis(); //Salva tempo atual

    Function call draw if you're on the button:

    void verificaTempo(){ 
        int passedTime05 = millis() - savedTime05;
        println("Verificando Tempo - PassedTime/TotalTime/SavedTime : " + passedTime05 + " - " + totalTime05 + " - " + savedTime05 );
    
        if (passedTime05 > totalTime05) {
          println("Click automático...");
          mousePressed();
          clicouMouse = true;     //Controle para somente uma vez, quando está com o foco sobre o mouse 
          savedTime05 = millis(); //Salva tempo atual
        }
      }
    

    If I had run "click" should have performed this function, but it is not running ...

    void controlEvent(ControlEvent theControlEvent) {
        println("PressMouse2: " + pressMouse2);
        if (pressMouse2){
          println("LInk: " + theControlEvent.controller().getLabel());
          opcaoLink = int(theControlEvent.controller().getValue());
    
          if (opcaoLink == 1){ //Definido Link para abrir página
            link(theControlEvent.controller().getLabel()); //Change to getStringValue...
          } else { //Escolher entre duas opções para abrir página    
            imgPai = int(theControlEvent.controller().getLabel());
    
            PApplet animacao07 = new Animacao07();  
            runSketch(new String[] { "***Vídeos***" }, animacao07);
          }
        }
      }
    

    Could you give any suggestions on how to simulate the "Click"

    Thank you for your attention again

  • Ha yes, I missed it when pressed simulates the mouse ...

    void mousePressed(){
        pressMouse2 = true;
        println("Pressionou Mouse");
    }
    

    Thank you

  • Hello,

    I could solve the problem of automatic Click the mouse, using the Robot class, I'll leave some of the code here, because I think it can be useful to someone else.

    in draw looked like this:

    if (tempoAutClick && focused){
          if (Collections.disjoint(cp5_05.getMouseOverList(), targets)==false) {
            if(cp5_05.getMouseOverList().size()==1) {
              verificaTempo();
            }
          } else {
            savedTime05 = millis();
          }
        } else {
          savedTime05 = millis();
        }
    

    The function verificaTempo

    void verificaTempo(){ 
        int passedTime05 = millis() - savedTime05;
    
        if (passedTime05 > totalTime05) {
          savedTime05 = millis(); //Salva tempo atual
          cliCkMouse();
          pressMouse2 = true;
        }
      }
    

    The function ClikMouse:

    static void cliCkMouse(){
       rob.mousePress(MouseEvent.BUTTON1_MASK);
       rob.mouseRelease(MouseEvent.BUTTON1_MASK);
    }
    

    Notes: The Click runs in the coordinate that is the mouse ...

    Thank you,

  • Hello,

    Continuing disruption to you ...

    You can find out some more information about the button, just being the mouse cursor over it, without the need to press?

    For example, you need to know what the x and y coordinates, you could not draw ControlEvent function (that is thrown in the mouse Click)

    To do this, for to draw a bar (for example) to indicate it is elapsing time, that at a certain time, runs the click of the mouse (Automatic Mouse Click)

    Thank you for your attention to whether you can help again.

Sign In or Register to comment.