无法在javafx中对齐框中的文本和按钮

时间:2013-08-16 06:49:21

标签: java javafx

以下是我发生错误或警告时显示对话框的代码, 但我无法对齐文本和按钮。两件事都相互遮挡。

    //INITIALIZING SCENE FOR dialogStage 
    StackPane dialogStackPane = new StackPane();
    dialogStackPane.setAlignment(Pos.CENTER);
    dialogStackPane.setLayoutX(0);
    dialogStackPane.setLayoutY(0);
    dialogStackPane.setPrefWidth(250.0);
    dialogStackPane.setPrefHeight(150.0);

    // dialogStage height and width
    dialogStage.setHeight(150.0);
    dialogStage.setWidth(250.0);

    //Scene for dialogStage
    sceneDialog = new Scene(dialogStackPane, 150.0, 250.0);
    sceneDialog.getStylesheets().add("/styles/Login.css");

    // Dialog box button
    btnDialog = new Button("close");
    btnDialog.setMinSize(10.0, 20.0);
    ObservableList ol = dialogStackPane.getChildren();
    ol.add(textWarning);
    ol.add(btnDialog);
    textWarning.setX(0);
    textWarning.setY(0);

    btnDialog.setLayoutX(0); 
    btnDialog.setLayoutY(0);

    // SETTING THE MODALITY OF THE DIALOG BOX
    dialogStage.initModality(Modality.APPLICATION_MODAL);
    dialogStage.setTitle("Warning");
    dialogStage.setScene(sceneDialog);        

    // Setting event listener on warning dialogStage button b
    btnDialog.addEventFilter(MouseEvent.ANY, new EventHandler<MouseEvent>() {
        // This handles the Mouse event of the dialog box button.
        @Override
        public void handle(MouseEvent t) {
            if (t.getEventType() == MouseEvent.MOUSE_CLICKED) {
                dialogStage.close();
            }
        }
    });

    textWarning.setLayoutX(20);
    textWarning.setLayoutY(200);

// textWarning.setTextOrigin(VPos.TOP); // textWarning.setTextAlignment(TextAlignment.LEFT);

    // Sets the warning box
    dialogStage.setResizable(false);      

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

使用AnchorPane代替StackPane。然后,您可以通过AnchorPane类中的静态方法定位任何节点。

AnchorPane pane = new AnchorPane();
...
AnchorPane.setLeftAnchor(textWarning, 50.0);
AnchorPane.setLeftAnchor(btnDialog, 50.0);
AnchorPane.setTopAnchor(textWarning, 20.0);
AnchorPane.setTopAnchor(btnDialog, 50.0);
...
pane.getChildren().addAll(textWarning, btnDialog);
...
sceneDialog = new Scene(pane, 150.0, 250.0);
...