2017-04-18 36 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

相关问题