How to display a button with an image only in the desired tab?

前端 未结 1 767
北恋
北恋 2021-01-26 12:01

I have OKNO1 and OKNO2, I want to show a button with an image strictly in OKNO1.

At the moment, the button with the image is shown globally. I used to u

相关标签:
1条回答
  • 2021-01-26 12:21

    Help others (including myself) help you:

    • keep the code tidy (remove anything that is unnecessary, like the getImage for example)
    • format the code so it's easy to read. I can't stress this enough.

    To help yourself always make sure you understand all your code completely:

    • read it
    • imagine in your head how it would run
    • run it and observe the actual behaviour
    • understand what was different between your mental model and what the computer did.

    This will help you debug code in general. Also checkout Kevin Workman's Debugging tutorial.

    Regarding your issue: the button is rendered all the time in draw(). You want to only draw it when the first tab is active hence:

    • get the first tab
    • check if it's active
    • if so, render the button

    e.g instead of button.draw() you'd use:

    if(cp5.getTab("default").isActive()){
        button.draw();
      }
    

    That will do the trick, but as you interface gets more complex, you may want group what's being drawn per tab. Here's an idea on how to organise for a UI with more controls per tab:

    • add a global variable (at the top of your code) to keep track of the current tab: int currentTab = 1;
    • call displayTabs(); in draw() instead of button.draw() to handle per tab drawing. (More about displayTabs() bellow)
    • controlEvent() to update the currentTab

    Like so:

    void controlEvent(ControlEvent event) {
      // update current tab only if the current event comes from a tab (and not other controllers) 
      if(event.isTab()){
        currentTab = event.getId();
      }
    }
    

    The idea is controlEvent will get triggered when any ControlP5 component (controller) is clicked/updated. If it's a tab you can update currentTab to know in draw() which content to draw() using displayTabs():

    void displayTabs(){
      switch(currentTab){
        case 1:
          displayTab1();
          break;
        case 2:
          displayTab2();
          break;
      }
    }
    
    void displayTab1(){
      button.draw();
    }
    
    void displayTab2(){
      // render stuff for tab 2 only
    }
    

    So there's one switch with calls one function or another depending on the currentTab value. The advantage of doing things this was is that you can easily replicate another case for another tab in the future and each tab content is neatly compartmentalised.

    0 讨论(0)
提交回复
热议问题