试图尽可能清楚这个程序应该显示随机选择的4张牌,然后在它们下方有一个按钮,可以从52的牌组随机重置所有牌。但是我对如何在动作活动中解决这个问题。 (也作为一个额外的奖励我似乎无法显示在卡片下面的按钮而不是我最终将整个屏幕从卡片和按钮移开)任何帮助将不胜感激。
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.scene.control.Button;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.layout.GridPane;
import javafx.event.ActionEvent;
public class GenerateCards extends Application {
public static void main(String[] args) {
Application.launch(args);
}
public int cardNum(){
int Num = (int) Math.ceil(Math.random()*52);
return Num;
}
public void start(Stage primaryStage) {
primaryStage.setTitle("Random Card");
GridPane pane = new GridPane();
pane.setAlignment(Pos.CENTER);
pane.setHgap(10);
pane.setVgap(5);
// creates button
Button refresh = new Button("Refresh");
HBox button = new HBox(10);
button.setAlignment(Pos.BOTTOM_CENTER);
button.getChildren().add(refresh);
pane.getChildren().add(refresh);
// creates random card images and adds them to pane
Image img = new Image("card/"+cardNum()+".png");
ImageView imgView = new ImageView(img);
pane.add(imgView, 1, 0);
Image img2= new Image("card/"+cardNum()+".png");
ImageView imgView2 = new ImageView(img2);
pane.add(imgView2, 2, 0);
Image img3= new Image("card/"+cardNum()+".png");
ImageView imgView3 = new ImageView(img3);
pane.add(imgView3, 3, 0);
Image img4= new Image("card/"+cardNum()+".png");
ImageView imgView4 = new ImageView(img4);
pane.add(imgView4,4, 0);
//create scene
Scene scene = new Scene(pane,400,200);
primaryStage.setScene(scene);
primaryStage.show();
refresh.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e){
// where im confused
}
});
}
}
答案 0 :(得分:1)
在您的按钮操作处理程序中,您只需重置每个图像视图中的图像。
refresh.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
imgView.setImage(new Image("card/" + cardNum() + ".png"));
imgView2.setImage(new Image("card/" + cardNum() + ".png"));
imgView3.setImage(new Image("card/" + cardNum() + ".png"));
imgView4.setImage(new Image("card/" + cardNum() + ".png"));
}
});
答案 1 :(得分:0)
Math.random()*4
会返回0到4之间的数字。首先,将img
,img2
,img3
和img4
添加到ArrayList
。然后从上述函数中获取随机索引,在ArrayList
中获取该索引处的图像,然后刷新它。