2017-04-18 48 views
1

所以我做了原本粉紅色的矩形變爲橙色鼠標點擊如何切換顏色之間/更改每次點擊鼠標時的時間?[JavaFX的]

public void start(Stage frame) throws Exception { 

    final Rectangle rectangle = new Rectangle(); 


    rectangle.setX(50); 
    rectangle.setY(50); 
    rectangle.setWidth(100); 
    rectangle.setHeight(50); 
    rectangle.setStroke(Color.BLACK); 
    rectangle.setFill(Color.PINK); 

    Pane pane = new Pane(); 

    pane.getChildren().add(rectangle); 

    Scene scene = new Scene(pane, 200, 200); 

    frame.setScene(scene); 
    frame.show(); 

    scene.setOnMouseClicked(new EventHandler <MouseEvent>(){ 
     public void handle(MouseEvent mouse) { 
      rectangle.setFill(Color.ORANGE); 

      } 

    }); 





} 

當我想要做的就是我希望它在每次點擊時在這兩種顏色(橙色的粉紅色&)之間切換。

我不想使用getClickCount()方法,因爲我無法再通過一次點擊就將它變成粉紅色,而不是兩次點擊。

我也希望每次按順序點擊它時都會改變一組顏色。

我不知道如何去做。我正在使用eclipse。

回答

1

粉色,橙色只需撥動基於當前顏色顏色:

rect.setOnMouseClicked(event -> { 
    Color curFill = rect.getFill(); 
    if (Color.ORANGE.equals(curFill) { 
     rect.setColor(Color.PINK); 
    } else if (Color.PINK.equals(curFill)) { 
     rect.setColor(Color.ORANGE); 
    } else { 
     // Shouldn't end up here if colors stay either Pink or Orange 
    } 
}); 

如果你想要的顏色任意數量的序列之間進行切換,把顏色到ArrayList和跟蹤

Color[] colors = new Color[size]; // class variable - fill with appropriate colors 
int curIndex = 0; // class variable 

rect.setOnMouseClicked(event -> { 
    curIndex = curIndex >= colors.length - 1 ? 0 : curIndex + 1; 
    rect.setFill(colors[curIndex]); 
}); 

注:當前指數的我使用的Java 8個Lambda表達式爲EventHandler S,但就像你在你發佈的代碼做你總是可以使用匿名類。

+0

工程非常棒!多謝 – MrBlock2274

相關問題