每次单击鼠标时如何在颜色之间切换/切换?[JavaFX]

时间:2017-04-18 11:11:56

标签: java 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 个答案:

答案 0 :(得分: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]);
});

注意:我为EventHandler使用了Java 8 Lambdas,但您可以像在发布的代码中一样使用匿名类。