所以我让原本粉红色的矩形在点击鼠标时变成橙色
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);
}
});
}
我想要做的是每次单击时我希望它在这两种颜色(粉色和橙色)之间切换。
I do not want to use getClickCount() method because I couldn't get it to pink color again in one click instead of two clicks.
我还希望每次按顺序单击时它都会更改一组颜色。
我不知道该怎么做。我正在使用 Eclipse。
最佳答案
对于粉橙色,只需根据当前颜色切换颜色:
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
}
});
如果您希望按顺序切换任意数量的颜色,请将颜色放入 Array
或 List
中并跟踪当前索引:
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
,但您始终可以使用匿名类,就像您在发布的代码中所做的那样。
关于java - 每次单击鼠标时如何在颜色之间切换/更改?[JavaFX],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43470561/