Reputation: 9344
I am making a simple click to change the images(src) of ImageView with button click. But the images should load randomly from directory. I created variables and used Random function to achieve this but got stuck creating and linking the function with even.
And Here is the complete Java code:
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();
}
}
}
Upvotes: 3
Views: 7445
Reputation: 9344
Removed Following:
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);
}
Adding the following code at the end helped.
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"));
}
Upvotes: 1