将一个事件的结果作为参数传递给JavaFx中的另一个事件

时间:2017-05-22 00:37:48

标签: javafx

假设我有两个MenuItemOpenRun。如何将Open操作的结果传递给Run

我尝试过的事情:

    // set up parent menus
    Menu fileMenu = new Menu("File");
    Menu controlMenu = new Menu("Control");

    // set up Open
    MenuItem openFile = new MenuItem("Open");
    openFile.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            FileChooser fileChooser = new FileChooser();
            File file = fileChooser.showOpenDialog(primaryStage);
        }
    });

    // set up Run
    MenuItem runControl = new MenuItem("Run");
    runControl.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            feeder = new Feeder();
            // file is a local variable cannot be passed to this event
            feeder.fillNewsBuffer(file); // where the problem occurs
        }
    });

    // add menu items
    fileMenu.getItems().addAll(
            openFile);
    controlMenu.getItems().addAll(
            runControl);

    // set up menu bar
    MenuBar menuBar = new MenuBar();
    menuBar.getMenus().addAll(fileMenu,controlMenu);

1 个答案:

答案 0 :(得分:1)

您已经发现file是一个局部变量,那么为什么不将file移到MenuItem共有的范围内?此外,根据文件是否已打开,使run项更改其disable状态更有意义。

// Declare it here
final ObjectProperty<File> openedFile = new SimpleObjectProperty<>();

// set up parent menus
Menu fileMenu = new Menu("File");
Menu controlMenu = new Menu("Control");

// set up Open
MenuItem openFile = new MenuItem("Open");
openFile.setOnAction(new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent event) {
        FileChooser fileChooser = new FileChooser();
        openFile.set(fileChooser.showOpenDialog(primaryStage));
    }
});

// set up Run
MenuItem runControl = new MenuItem("Run");
runControl.disableProperty().bind(Bindings.createBooleanBinding(() -> openedFile.get() == null, openedFile));
runControl.setOnAction(new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent event) {
        feeder = new Feeder();
        if (openedFile.get() != null)
            feeder.fillNewsBuffer(openedFile.get());
    }
});

// add menu items
fileMenu.getItems().addAll(
        openFile);
controlMenu.getItems().addAll(
        runControl);

// set up menu bar
MenuBar menuBar = new MenuBar();
menuBar.getMenus().addAll(fileMenu,controlMenu);