1
我正在做一个简单的点击,用按钮点击来改变ImageView的图像(src)。但图像应该从目录中随机加载。我创建了变量,并使用Random函数来实现这一点,但创建并将函数与even链接在一起。如何使用鼠标在Javafx上单击来更改ImageView的图像(src)?
,这里是完整的Java代码:
public class CardsGame extends Application {
// Variables
String img1, img2, img3;
ArrayList<String> array = new ArrayList<>();
public CardsGame() {
for (int i = 0; i < 68; i++) {
array.add("imagescards/" + i + ".png");
}
img1 = (String) array.get((int) (Math.random() * 67) + 1);
img2 = (String) array.get((int) (Math.random() * 67) + 1);
img3 = (String) array.get((int) (Math.random() * 67) + 1);
}
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) {
// Create FlowGrid
FlowPane pane = new FlowPane();
pane.setPadding(new Insets(5, 5, 5, 5));
// Create Image View
ImageView cardImg1 = new ImageView(("imagescards/1.png"));
cardImg1.setFitHeight(200);
cardImg1.setFitWidth(150);
ImageView cardImg2 = new ImageView(("imagescards/2.png"));
cardImg2.setFitHeight(200);
cardImg2.setFitWidth(150);
ImageView cardImg3 = new ImageView(("imagescards/1.png"));
cardImg3.setFitHeight(200);
cardImg3.setFitWidth(150);
// Create Button
Button play = new Button("Play");
play.setMinWidth(100.0);
play.setOnAction(new EnlargeHandler());
// Add nodes to pane
pane.getChildren().addAll(cardImg1, cardImg2, cardImg3, play);
// Create Scene
Scene scene = new Scene(pane, 460, 250);
// Add scene to stage
primaryStage.setScene(scene);
primaryStage.setTitle("Cards Game");
// Show Stage
primaryStage.show();
}
public void refresh() {
img1 = (String) array.get((int) (Math.random() * 67) + 1);
img2 = (String) array.get((int) (Math.random() * 67) + 1);
img3 = (String) array.get((int) (Math.random() * 67) + 1);
}
class EnlargeHandler implements EventHandler<ActionEvent> {
@Override
public void handle(ActionEvent event) {
refresh();
}
}
}