0

我正在尝试组合我拥有的多个草图,将它们作为类放在一个草图中并通过按键浏览它们。

我不确定我是否采用了正确的方法,但我基本上是通过对每个使用布尔值来打开和关闭它们。我有类似的东西:

package combiner;

public class Combiner extends PApplet {
    //...
    ClassNameOne s1;
    ClassNameTwo s2;
    //...
    ClassNameNine s9;

    // AllSketches //
    boolean[] sketches;
    int totalSketches = 9;
    String str_ts = String.valueOf(totalSketches);
    char char_ts = str_ts.charAt(0);

    public void setup() {
            size(1920, 1080);

            sketches = new boolean[totalSketches];
            for (int i = 0; i < sketches.length; i++) {
            sketches[i] = false;
            }

            s1 = new ClassNameOne(this);
            s2 = new ClassNameTwo(this);
            //...
            s9 = new ClassNameNine(this);
    }

    public void draw() {
            //drawingEachSketchIfItsBoolean==True
            if (sketches[0] == true) {
            s1.run();
            } else if (sketches[1] == true) {
            s2.run();
            //....
            }
    }

    public void keyPressed() {
            if (key >= '1' && key <= char_ts) {
                    String str_key = Character.toString(key);
                    int KEY = Integer.parseInt(str_key);

                    for (int i = 0; i < sketches.length; i++) {
                    sketches[i] = false;
                    }
                    sketches[KEY - 1] = true;

                    //initializingEachClassIfKeyPressed
                    if (KEY == 0) {
                    s1.init();
                    } else if (KEY == 1) {
                    s2.init();
                    }
                    //....
            }
    }

如您所见,每个类都有一个 .init 和一个 .run 方法(以前是我的 setup + draw)。如果我可以以某种方式循环到 .init 或 .run 它们而不必为每个编写一次,我就在徘徊,例如:

for(int i=0;i<sketches.length;i++){
    if(sketches[i]==true){
        String str = String.valueOf(i+1);
        str="s"+str; //str becomes the Object's name
        ??? str.run(); ???
    }
}
4

2 回答 2

1

最干净的解决方案是创建一个接口 Sketch,然后必须在您的草图类中实现它:

Sketch[] sketches;
int activeSketch = 0;

void setup(){
  sketches = new Sketch[2];
  sketches[0] = new SketchRed();
  sketches[1] = new SketchGreen();
  sketches[activeSketch].init();
}

void draw(){
  sketches[activeSketch].draw();
}

interface Sketch{
  void init();
  void draw();
}

class SketchRed implements Sketch{
  void init(){}

  void draw(){
    fill(255, 0, 0);
    ellipse(width/2, height/2, 30, 30);
  }
}

class SketchGreen implements Sketch{
  void init(){}

  void draw(){
    fill(0, 255, 0);
    ellipse(width/2, height/2, 30, 30);
  }
}

void keyPressed(){
  activeSketch++;
  if(activeSketch >= sketches.length){
    activeSketch = 0;
  }
  sketches[activeSketch].init();
}
于 2013-07-30T09:28:16.950 回答
0

我不确定将不同草图表示为新草图中的类的整个想法是否真的那么好,但无论如何,Java 中似乎有可能从字符串中获取类!Class.forName()按照此处所述查找:http: //docs.oracle.com/javase/tutorial/reflect/class/classNew.htm

请记住,您将从此获得一个类,而不是一个实例!

于 2013-07-26T14:39:59.833 回答