Quantcast
Channel: Library Questions - Processing 2.x and 3.x Forum
Viewing all articles
Browse latest Browse all 2896

Need a better way of creating a list of text field objects

$
0
0

Hi there,

Have constructed a bit of code that creates say 5 text fields along with corresponding submit buttons.

Have managed this with For Loops. Is there a more elegant way to do this?

I feel my code can be improved as it would be very cumbersome to keep copy-pasting and changing the relative numbers especially for the submit() function. The overall code would take up too much space.

Can the submit function reside within a for loop as well?

Would love to hear some ideas so that I can take it forward. Thanks!

Here is the code I'm using:

import controlP5.*;

ControlP5 cp5;

// Should we do an array for this initialization?
// I don't want to type out say 30 textValues. What is the more elegant way to represent this?
// Arrays.fill()??

String textValue_1 = "";
String textValue_2 = "";
String textValue_3 = "";
String textValue_4 = "";
String textValue_5 = "";

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

  for (int i = 1; i < 6; ++i) {
    cp5.addTextfield("textValue" + "_" + i)
      .setPosition(20, 80*i)
        .setSize(200, 40)
          .setFont(createFont("arial", 20))
            .setCaptionLabel("Enter Text for field " + i)
              .setAutoClear(false)
                ;

    cp5.addButton("submit"+ "_" + i)
      .setPosition(240, 80*i)
        .setSize(80, 40)
          .setCaptionLabel("submit")
            .getCaptionLabel().align(ControlP5.CENTER, ControlP5.CENTER)
              ;
  }
}

void draw() {
  background(0);
}

// The function for submit... can this be done in a for loop?
// I may want a large number of text fields
// and it can get tedious typing it all out every time I change the number


public void submit_1() {
  cp5.get(Textfield.class, "textValue_1").submit();
}

public void submit_2() {
  cp5.get(Textfield.class, "textValue_2").submit();
}

public void submit_3() {
  cp5.get(Textfield.class, "textValue_3").submit();
}

public void submit_4() {
  cp5.get(Textfield.class, "textValue_4").submit();
}

public void submit_5() {
  cp5.get(Textfield.class, "textValue_5").submit();
}


void controlEvent(ControlEvent theEvent) {
  if (theEvent.isAssignableFrom(Textfield.class)) {
    println("controlEvent: accessing a string from controller '"
      +theEvent.getName()+"': "
      +theEvent.getStringValue()
      );
  }
}

Viewing all articles
Browse latest Browse all 2896

Trending Articles