I am a beginner with programming and coding. I try to make random things to develop myself. I drawed a traffic light with JavaFX. Now I want to when I click on the button a random light will glow.
I've tried it with a switch and else elseif. I did not come to a solution
public StoplichtLayout(Pane l){
layout = l;
layout.setStyle("-fx-background-color: #777;");
button = new Button("Teken");
button.setLayoutX(10);
button.setLayoutY(10);
button2 = new Button("Random licht laten branden");
button2.setLayoutX(100);
button2.setLayoutY(10);
button.setOnAction(ev -> {
button();
});
this.layout.getChildren().add(button);
button2.setOnAction(ev -> {
});
this.layout.getChildren().add(button2);
}
private void button(){
Rectangle paal = new Rectangle(200, 300, 25, 200);
paal.setArcHeight(10);
paal.setArcHeight(10);
Rectangle bord = new Rectangle();
bord.setX(175);
bord.setY(175);
bord.setWidth(75);
bord.setHeight(150);
bord.setFill(Color.GREY);
bord.setStroke(Color.BLACK);
bord.setArcHeight(20);
bord.setArcWidth(20);
Circle roodlicht = new Circle(15);
roodlicht.setCenterX(213);
roodlicht.setCenterY(205);
roodlicht.setFill(Color.rgb(165, 0, 0));
roodlicht.setStroke(Color.BLACK);
Circle geellicht = new Circle(15);
geellicht.setCenterX(213);
geellicht.setCenterY(250);
geellicht.setFill(Color.rgb(188, 173, 54));
geellicht.setStroke(Color.BLACK);
Circle groenlicht = new Circle(15);
groenlicht.setCenterX(213);
groenlicht.setCenterY(295);
groenlicht.setFill(Color.rgb(9, 114, 0));
groenlicht.setStroke(Color.BLACK);
layout.getChildren().addAll(paal, bord, roodlicht, geellicht, groenlicht);
}
}
I expect that when I click on the button a random light will glow. I hope somebody can help me.
You expect that to happen yet you have no code there. Put your circles in an indexed collection such as an ArrayList then find a random one and light it up by lightening the color as below:
List<Circle> lights = new ArrayList<Circle>();
// add your circles to the list
Circle toLight = lights.get(new Random().nextInt(lights.size()));
// V setting the color to be brighter
toLight.setFill(((Color) toLight.getFill()).brighter());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.