如何不覆盖现有对象列表?

时间:2018-11-08 14:23:01

标签: processing line instance

我想在单击画布时画线,所以如果单击一次,则保存该点,如果单击第二次,则在这两个点的后面绘制一条线。但是,我想多次进行此操作,因此,如果我第三次单击,则此点将成为新行的起点。 我这样创建: 这是在main中:

ArrayList<Shape> shapes = new ArrayList<Shape>();
Shape selected_shape = null;

Boolean drawmode = true;


    void setup() {
      size(1000, 600);
    }

    void draw() {
      //update();
      background(224, 224, 224);

      //draw the existing
      for(Shape s: shapes){
        pushMatrix();
        //list all
        s.Draw();
        s.Log();
        popMatrix();
      }
      println("shape size: "+shapes.size());
    }

    //menu
    int value = 0;
    void keyPressed() {
      if(key == '0'){
          System.out.println("Draw mode OFF"); // exit from draw mode
          value = 0;
      }
      if(key == '1'){ 
          println("Draw a line: select the start point of the line and the end point!");  // line
          value = 1;
      }
      //System.out.println("key: " + key);
    }

    Line l = new Line();
    void mousePressed() {
      if(value == 1){
        if(l.centerIsSet){
          if (mouseButton == LEFT) {
            l.x2 = mouseX;
            l.y2 = mouseY;
            println("end point added");
            l.centerIsSet = false;
          }
          shapes.add(l);
          l.Log();
        } else {
          if (mouseButton == LEFT) {
            l.x1 = mouseX;
            l.y1 = mouseY;
            l.centerIsSet = true;
            println("start point added");
          }
        }
      }
    }

我使用shape类,并且该类通过line进行了扩展:

abstract class Shape {

  PVector position = new PVector();  
  PVector fill_color = new PVector(0, 0, 0);
  PVector stroke_color = new PVector(0, 0, 0);  
  PVector select_fill_color = new PVector(255, 0, 0);
  PVector select_stroke_color = new PVector(255, 0, 0);

  Boolean selected = false;

  int shape_color_r;
  int shape_color_g;
  int shape_color_b;
  int shape_rotation_angle = 0;

  int detailness = 10;

  abstract void Draw();
  abstract void Log();
}

和:

class Line extends Shape {
    int x1, x2, y1, y2;
    Boolean centerIsSet = false;

    Line(){}
    Line(int x1, int y1){
      this.x1 = x1;
      this.y1 = y1;
    }
    Line(int x1, int y1, int x2, int y2){
      this.x1 = x1;
      this.x2 = x2;
      this.y1 = y1;
      this.y2 = y2;
    }

    void Draw(){
      line(x1, y1, x2, y2);
    }

    void Log(){
      System.out.println("x1: "+x1+" x2: "+x2+" y1: "+y1+" y2: "+y2);
    }
}

但是最后创建的行总是会覆盖旧的行,我该如何解决呢?我想我需要为每行添加一个新实例,但是我不知道该怎么做。

1 个答案:

答案 0 :(得分:1)

变量l指向Line对象,该对象保存当前绘制的线的坐标。

如果完成了一行,则对行对象l的引用将添加到容器shapes中。现在,您必须为下一行创建一个新的行对象,并将其分配给l

shapes.add(l);
l = new Line();