2014-02-06 63 views
0

我已經完成了這個任務的大部分工作,但是一直讓我憤怒的部分是,一旦點擊了這個按鈕,它不僅必須變綠,而且必須保持綠色。我已經把它變成綠色,但保持綠色我只是無法弄清楚。我覺得我已經嘗試了一切。每次點擊鼠標時,我都使用了一個計數器,然後我製作了一個小的循環,當計數器大於0時啓動,並將綠色矩形放在按鈕上。我試過mouseReleased方法。我在這裏撕掉我的頭髮。處理:一個簡單的按鈕

void setup() { 
    size(600,400); 
    background(250); 
} 
void draw(){ 
    //if mouse pressed turn green 
//Checks if cursor is inside of button & turns it green when clicked 
    if(mouseX>250 && mouseY>150 && mouseX<350 && mouseY<200 && mousePressed==true){ 
    fill(42,255,15); 
    rect(250,150,100,50); 
} 
    //Turns button light grey when cursor is hovered over it. 
    else if(mouseX>250 && mouseY>150 && mouseX<350 && mouseY<200){ 
    fill(175); 
    rect(250,150,100,50); 
    } 
    //Turns button med grey when cursor is outside of button 
    else{ 
    fill(131); 
    rect(250,150,100,50); 
    } 
} 

回答

0

隨着你的代碼最小的調整,這是一個解決方案,您可以使用一個布爾值,標誌,如果該按鈕被點擊了,事情是,mousePressed保持狀態的鼠標的按鍵時,所以只要你釋放它的變種會拿着假的,所以裏邊反旗四處:

車工作示例代碼...

boolean clicked = false; 

void setup() { 
    size(600, 400); 
    background(250); 
} 
void draw() { 
    //if mouse pressed turn green 
    //Checks if cursor is inside of button & turns it green when clicked 

    if (mouseX>250 && mouseY>150 && mouseX<350 && mouseY<200) { //if hoover 
    if (clicked) {// and clicked 
     fill(101, 131, 101);// dark green 
    } 
    else {// not clicked 
     fill(131);//darker gray 
    } 

    if (mousePressed) {// if hover and clicked... change flag 
     clicked = !clicked; // toogle boolean state 
    } 
    } 
    else {//not hovering 

    if (clicked) { // and clicked 
     fill(42, 255, 15);// green 
    } 
    else { 
     fill(175);//gray 
    } 
    } 
    rect(250, 150, 100, 50);// draw anyway... 
} 

您可能還需要檢查mousePressed()功能,而不是mousePressed,現場你正在使用。 .. 但是這樣一來它的工作原理,而不是這麼好艱難,你可以修復,而無需使用mousePressed()但也有一些額外的代碼......我更喜歡使用的功能,一個例子是:

boolean clicked = false; 

void setup() { 
    size(600, 400); 
    background(250); 
} 
void draw() { 
    if (mouseX>250 && mouseY>150 && mouseX<350 && mouseY<200) { //if hoover 
    if (clicked) {// and clicked 
     fill(101, 131, 101);// dark green 
    } 
    else {// not clicked 
     fill(131);//darker gray 
    } 
    } 
    else {//not hovering 

    if (clicked) { // and clicked 
     fill(42, 255, 15);// green 
    } 
    else { 
     fill(175);//gray 
    } 
    } 
    rect(250, 150, 100, 50);// draw anyway... 
} 

void mouseReleased() { 
    clicked = !clicked; 
} 
+0

非常感謝。我想我絕對可以從這裏弄明白。 –