2017-09-07 39 views
1

什么是最容易和最简单的方法来保持fill()相同点击后(那是当它改变),然后unclicking,并离开悬停?如何在mousePressed后填充()中的颜色相同?

在这个项目中,我只是做了一个网格。当鼠标悬停在特定矩形(在x,y上)时,它会根据所处状态改变颜色。fill(50)是默认设置,fill(75)是鼠标悬停的时候,fill(100)是鼠标单击的时候。但是,当鼠标点击时,它会返回到悬停填充状态,直到鼠标离开矩形。谢谢。

int cols, rows; 
int scl = 20; 

void setup() { 
size(400, 400); 
int w = 400; 
int h = 400; 
cols = w/scl; 
rows = h/scl; 
} 

void draw() { 
background(255); 

    for (int x = 0; x < cols; x++) { 
    for (int y = 0; y < rows; y++) { 
     int xpos = x*scl; 
     int ypos = y*scl; 
     stroke(55); 
     if((mouseX >= xpos && mouseX <= xpos+scl) && 
     (mouseY >= ypos && mouseY <= ypos+scl)){ 
     fill(75); 
     if (mousePressed == true){ 
      println("Clicked at: " + xpos + " and " + ypos); 
      fill(100); 
     //here is the desired location for the fill to remain constant even 
     //after unclicking and leaving hover 
     } 
     println("Mouse at: " + xpos + " and " + ypos); 
     }else{ 
     fill(50); 
     } 

     rect(xpos, ypos, scl, scl); 
    } 
    } 
} 
+0

你能否修改你的代码的格式?你有两个'setup()'函数。你也可以更具体地说明你想要做什么,哪一行代码的行为与你期望的不同? –

+0

对不起,我没有看到!如果现在运行代码,您会注意到当您将鼠标悬停在矩形上时,它会更改颜色,并且当您单击它时会再次更改颜色。 “mousePressed”后面使用的填充颜色是我想用来保持单击的方块其点击的颜色。 – Icy4614

回答

1

堆栈溢出并不是真正为一般的“我该怎么做”类型的问题而设计的。这是针对具体的“我试过X,预计Y,但得到Z”类型的问题。但我会尝试在一般意义上提供帮助:

您需要将每个单元格的状态存储在数据结构中,然后使用该数据结构绘制场景。

你可以用二维数组来做到这一点,其中数组中的每个单元格表示网格中的一个单元格。您可以直接存储单元格的状态或颜色。

+0

我会尝试类似的东西,并且Processing可以让你在控制台中看到打印的数组,但它总是显示类似''[[I @ 4e59b084''的东西,不知道它是什么意思。 编辑:另外,我怎么能设置这个2D数组的骨架? – Icy4614

+0

@ Icy4614这是因为默认行为是打印出数组的哈希码。你可能会考虑编写自己的函数来打印数组中的值,或者在Java API中查找可能有帮助的函数。 –

1

正如Kevin所说,你应该将你的应用程序的状态保存在一个矩阵中。

boolean[][] matrix = new boolean[21][21]; 

当你点击一个cell,拨动它

if(!matrix[xpos/scl][ypos/scl]) { 
    matrix[xpos/scl][ypos/scl] = true; 
} else { 
    matrix[xpos/scl][ypos/scl] = false; 
} 

在这个循环中,检查您的当前位置,可以得出与否

if(matrix[x][y]) { 
    fill(204, 102, 0); // an orange color 
    rect(xpos, ypos, scl, scl); 
} 

所以你draw()方法应该看像这样

void draw() { 
    background(255); 
    for (int x = 0; x < cols; x++) { 
     for (int y = 0; y < rows; y++) { 
      int xpos = x*scl; 
      int ypos = y*scl; 

      stroke(55); 
      if((mouseX >= xpos && mouseX <= xpos+scl) && 
        (mouseY >= ypos && mouseY <= ypos+scl)){ 
       fill(75); 
       if (mousePressed == true){ 
        println("Clicked at: " + xpos + " and " + ypos); 
        if(!matrix[xpos/scl][ypos/scl]) { 
         matrix[xpos/scl][ypos/scl] = true; 
        } else { 
         matrix[xpos/scl][ypos/scl] = false; 
        } 
        fill(100); 
        //here is the desired location for the fill to remain constant even 
        //after unclicking and leaving hover 
       } 
       println("Mouse at: " + xpos + " and " + ypos); 
      }else{ 
       fill(50); 
      } 
      if(matrix[x][y]) { 
       fill(204, 102, 0); 
       rect(xpos, ypos, scl, scl); 
      } 
      rect(xpos, ypos, scl, scl); 
     } 
    } 
} 
+0

哇!这正是我所需要的。谢谢! – Icy4614