0

I have a:

  • TreeView with ContextMenu and one MenuItem called "New File"
  • Toolbar with Button also called "New File"
  • Function with InputDialog and File creation

What would be a good approach to share functionality between a context menu and a toolbar? Static class, Singleton or is there something better?

I don't want to create the same function twice.

  • Just have the handlers for each call the same method? Without some actual context it's not really clear what the issue is. – James_D Feb 20 '16 at 21:01

2 Answers2

1

This should be fairly straightforward as long as your program is already structured to handle such shared functionality. A good pattern to follow, particularly if you haven't before (as a learning exercise) is Model-View-Controller (MVC). You should be able to find (through an internet search) a tutorial to implement MVC on JavaFX.

In this case, you'd be looking at two different parts of your Controller, and pointing them both at the same element (your New File functionality) in your Model.

mech
  • 2,775
  • 5
  • 30
  • 38
  • 1
    [Example of MVC in JavaFX](http://stackoverflow.com/questions/32342864/applying-mvc-with-javafx) if you need it. – James_D Feb 20 '16 at 21:23
0

I think this could work well:

public void start(Stage stage) throws Exception {
    // Other code...

    MenuItem newFile = new MenuItem("New file...");
    Button button = new Button("New File...");

    contextMenu.getItems().add(newFile);
    toolbar.getItems().add(button);

    button.setOnAction(new Handler());
    newFile.setOnAction(new Handler());

    borderPane.setTop(toolbar);
    borderPane.setCenter(treeView);
    treeView.setContextMenu(menu);

    // Other code...
}

And here the Handler:

public class Handler implements EventHandler<ActionEvent> {

    @Override
    public void handle(ActionEvent event) {
        // Handle the creation of the file
    }

}
aleb2000
  • 452
  • 4
  • 10