繁体   English   中英

如何在同一控制器JavaFX中制作弹出菜单?

[英]How to make popup menu in same controller JavaFX?

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

但是,新场景是另一个具有其自己的控制器的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>

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

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!");
            }
        }

    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM