如何通过按钮鼠标单击Javafx来更改ImageView的图像(src)?

时间:2016-02-12 15:44:36

标签: java javafx

我点击一下即可通过按钮点击更改ImageView的图像(src)。但是图像应该从目录中随机加载。我创建了变量并使用了Random函数来实现这一点但却陷入了创建和连接函数的问题。

enter image description here

以下是完整的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();
        }
    }

}

1 个答案:

答案 0 :(得分:0)

删除了以下内容:

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);
}

最后添加以下代码有帮助。

play.setOnAction(new EventHandler<ActionEvent>() {
      public void handle(ActionEvent e) {
      cardImg1.setImage(new Image("imagescards/" + CardsGame() + ".png"));
      cardImg2.setImage(new Image("imagescards/" + CardsGame() + ".png"));
      cardImg3.setImage(new Image("imagescards/" + CardsGame() + ".png"));
 }