【问题标题】:How to make popup menu in same controller JavaFX?如何在同一控制器 JavaFX 中制作弹出菜单?
【发布时间】:2018-06-01 18:08:15
【问题描述】:

在我的代码中制作弹出菜单时遇到问题,我设置它的方式是,如果单击按钮,它将打开一个新场景(如果他们想删除某些内容,则会提示)

然而,这个新场景是另一个带有它自己的控制器的 FXML 文件,当我试图让新的 FXML 控制器删除一些东西时,它不起作用,因为代码不在同一个控制器中,所以我不能从 FIRST 控制器执行代码。

现在我只想能够在同一个类中打开一个对话,我不知道如何将代码转换为在同一个控制器中。这是我想保留在同一个控制器中的 FXML 代码

<AnchorPane id="AnchorPane" prefHeight="89.0" prefWidth="388.0" 
xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8" 
fx:controller="finalprojectjava.DeletePopupController">
   <children>
  <Label layoutX="48.0" layoutY="14.0" prefHeight="32.0" prefWidth="293.0" text="Are you sure you want to delete contact?">
     <font>
        <Font size="16.0" />
     </font>
  </Label>
  <Button layoutX="92.0" layoutY="50.0" mnemonicParsing="false" onAction="#acceptButton" prefHeight="25.0" prefWidth="91.0" text="Yes" />
  <Button layoutX="195.0" layoutY="50.0" mnemonicParsing="false" onAction="#declineButton" prefHeight="25.0" prefWidth="91.0" text="No" />
   </children>
</AnchorPane>

【问题讨论】:

标签: java eclipse javafx netbeans fxml


【解决方案1】:

这是一个使用 JavaFX 对话框通过弹出窗口获取用户响应的示例。您可以了解更多关于此 API 的强大功能here

public class Main extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {

        VBox pane = new VBox(10);
        pane.setPadding(new Insets(10));

        Button btnShowDialog = new Button("Show Popup");
        // Set the action to call the showPopup() method when clicked
        btnShowDialog.setOnAction(e -> showPopup());

        pane.getChildren().add(btnShowDialog);

        Scene scene = new Scene(pane);
        primaryStage.setScene(scene);

        primaryStage.show();
    }

    private void showPopup() {

        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setTitle("Delete Contact?");
        alert.setHeaderText("Are you sure you want to delete this contact?");

        // Set the available buttons for the alert
        ButtonType btnYes = new ButtonType("Yes");
        ButtonType btnNo = new ButtonType("No");

        alert.getButtonTypes().setAll(btnYes, btnNo);

        // This allows you to get the response back from the user
        Optional<ButtonType> result = alert.showAndWait();

        if (result.isPresent()) {
            if (result.get() == btnYes) {
                System.out.println("User clicked Yes!");
            } else if (result.get() == btnNo) {
                System.out.println("User clicked No!");
            }
        }

    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    相关资源
    最近更新 更多