在StackPane
中,HBox
ES將要被調整,以填補StackPane
。因此這兩個HBox
都填充整個區域,對齊設置將按鈕定位在其中。因此,雖然按鈕實際上不重疊,但HBox
es。
StackPane
(和其他窗格,在某些情況下)中的節點的z順序由children
列表中的節點順序決定。因此,在您的代碼中,buttonContainer
位於「後面」roomContainer
。這意味着鼠標點擊的目標要麼是roomContainer
中的按鈕,要麼是roomContainer
本身。因此,buttonContainer
中的按鈕永遠不會收到鼠標點擊。
解決方案是使用「真實」佈局容器來適當定位兩個按鈕容器。例如,你可以使用一個AnchorPane
:
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Game extends Application {
public static void main(String[] args) {
launch(args);
}
Button attack, run, drinkPotion, nextRoom;
AnchorPane root;
HBox buttonContainer, roomContainer;
Scene scene;
public void createNode() {
root = new AnchorPane();
scene = new Scene(root, 860, 640);
attack = new Button("Attack");
run = new Button("Run!");
drinkPotion = new Button("Drink Potion!");
nextRoom = new Button("Go to next room...");
buttonContainer = new HBox(12);
buttonContainer.getChildren().addAll(attack, run, drinkPotion);
roomContainer = new HBox();
roomContainer.getChildren().addAll(nextRoom);
AnchorPane.setBottomAnchor(buttonContainer, 0.0);
AnchorPane.setLeftAnchor(buttonContainer, 0.0);
AnchorPane.setBottomAnchor(roomContainer, 0.0);
AnchorPane.setRightAnchor(roomContainer, 0.0);
root.getChildren().addAll(roomContainer, buttonContainer);
}
@Override
public void start(Stage stage) {
createNode();
stage.setScene(scene);
stage.show();
}
}
或可能是BorderPane
:
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class Game extends Application {
public static void main(String[] args) {
launch(args);
}
Button attack, run, drinkPotion, nextRoom;
BorderPane root;
HBox buttonContainer, roomContainer;
Scene scene;
public void createNode() {
root = new BorderPane();
scene = new Scene(root, 860, 640);
attack = new Button("Attack");
run = new Button("Run!");
drinkPotion = new Button("Drink Potion!");
nextRoom = new Button("Go to next room...");
buttonContainer = new HBox(12);
buttonContainer.getChildren().addAll(attack, run, drinkPotion);
buttonContainer.setAlignment(Pos.BOTTOM_CENTER);
roomContainer = new HBox();
roomContainer.getChildren().addAll(nextRoom);
roomContainer.setAlignment(Pos.BOTTOM_CENTER);
root.setLeft(buttonContainer);
root.setRight(roomContainer);
}
@Override
public void start(Stage stage) {
createNode();
stage.setScene(scene);
stage.show();
}
}
你可以閱讀所有的佈局窗格中tutorial
哪裏是對的OnAction如何工作的概述按鈕代碼? – Programmer
這個演示沒有setOnAction代碼。問題是如果我在StackPane中有兩組按鈕,FX不會讓我點擊一個按鈕。該按鈕被卡住,並沒有「點擊」動畫。 –