我是编程和编码方面的初学者。我试着做一些随机的事情来发展自己。我用 JavaFX 画了一个红绿灯。现在我想当我点击按钮时随机灯会发光。
我已经用 switch 和 elseif 试过了。我没有得出解决方案
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);
}
我希望当我点击按钮时,随机灯会发光。我希望有人能帮助我。
最佳答案
您希望发生这种情况,但您那里没有代码。将您的圈子放在一个索引集合中,例如 ArrayList,然后随机找到一个并通过照亮以下颜色来点亮它:
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());
关于java - 我怎样才能用红绿灯显示随机灯?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54136434/