[英]How to change image(src) of ImageView with button mouse-click on Javafx?
我只需單擊一下即可通過單擊按鈕更改ImageView的images(src)。 但是圖像應該從目錄中隨機加載。 我創建了變量,並使用Random函數實現了這一目標,但在創建函數並將其與Even連接時遇到了麻煩。
這是完整的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();
}
}
}
已刪除以下內容:
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"));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.