我有一個程序,它在屏幕上顯示3個隨機的象形文字圖像。我添加了「刷新」按鈕以刷新象形文字圖像。當我點擊按鈕時,圖像會正確刷新和隨機化。第一次點擊按鈕後,它會消失。我幾乎肯定它與我的pane.getChildren().clear();
產品線有關,但我似乎無法弄清楚。任何提示或建議?點擊1次後JavaFX刷新按鈕消失
如果我張貼不正確或沒有使用正確的指引,我很抱歉。這是我的第一篇文章。
這裏是我的代碼:
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.control.Button;
import javafx.geometry.Pos;
import javafx.scene.layout.HBox;
public class Lab6a extends Application {
@Override
public void start(Stage myStage) {
//Create an HBox layout.
HBox hBox1 = new HBox();
//Set alignment.
hBox1.setAlignment(Pos.CENTER);
getRandomHieroglyphic(hBox1);
//Create a Refresh button.
Button refresh = new Button("Refresh");
refresh.setOnAction(e -> getRandomHieroglyphic(hBox1));
hBox1.getChildren().add(refresh);
//Set the title for the second window.
myStage.setTitle("Random Hieroglyphics with Refresh");
//Create a scene for the window.
Scene myScene = new Scene(hBox1, 400, 400);
//Place the scene in the second window.
myStage.setScene(myScene);
//Show the stage.
myStage.show();
}
public void getRandomHieroglyphic(HBox pane) {
pane.getChildren().clear();
//Create random generators to get a random image
int randomInt1 = (int) (Math.random() * 9) + 1;
int randomInt2 = (int) (Math.random() * 9) + 1;
int randomInt3 = (int) (Math.random() * 9) + 1;
//Create paths for the images to be called
String path1 = "Image/Hieroglyphics/h" + randomInt1 + ".png";
String path2 = "Image/Hieroglyphics/h" + randomInt2 + ".png";
String path3 = "Image/Hieroglyphics/h" + randomInt3 + ".png";
//Add the images into the pane
pane.getChildren().add(new ImageView (path1));
pane.getChildren().add(new ImageView (path2));
pane.getChildren().add(new ImageView (path3));
}
public static void main(String[] args) {
launch(args);
}
}
您說得對。您的Hbox最初有4個小孩,3個圖像和按鈕。你應該在'getRandomHieroglyphic()'方法中添加按鈕。 –
但更好的辦法是將按鈕與圖像分開。最好的做法是在場景中添加一個'BorderPane',並將'HBox'的圖片放在'center'和'bottom'區域的按鈕中。 –