在StackPane 中,HBoxes 将调整大小以填充StackPane。所以这里的HBoxes 都填充了整个区域,对齐设置将按钮定位在其中。因此,虽然按钮实际上并没有重叠,但 HBoxes 会重叠。
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 中阅读所有布局窗格如何工作的概述