2017-09-07 37 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