Reputation: 6166
Suppose I have two MenuItem
: Open
and Run
. How could I pass the result from Open
action to Run
?
What I've tried:
// 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);
Upvotes: 0
Views: 87
Reputation: 8363
You have already figured out file
is a local variable, then why aren't you moving file
out to a scope that is common to both MenuItem
? Also, it makes more sense to make run
item change its disable
state based on whether a file has been opened or not.
// 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);
Upvotes: 1