假设我有两个MenuItem
:Open
和Run
。如何将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);
答案 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);