JavaFX FXML menuItem action


Question

I'm trying to set a variable value when a MenuItem i chosen in a MenuButton object. I've tried to search for this but I've came up empty handed.

Here's the code to set the MenuItems:

private ObservableList<MenuItem> templateMenuItems = FXCollections.observableArrayList();
@FXML private MenuButton menu = new MenuButton();

@FXML
protected void getTemplates() throws IOException {
    CaspReturn tls = this.socket.runCmd(new Tls(""));
    String tlsList = tls.getResponse();
    String[] tlsListSplitt = tlsList.split("\\n");
    for (int i = 0; i < tlsListSplitt.length; i++) {
        String[] tlsLine = tlsListSplitt[i].split("\"");
        this.templateMenuItems.add(new MenuItem(tlsLine[1]));
    }
    this.menu.getItems().setAll(this.templateMenuItems);
}

I'm not sure how to write the code to get the text from a menuItem or which field in scenebuilder the method should be in.

1
0
10/18/2014 9:42:40 AM

Accepted Answer

It's not clear what your asking, but I'll assume that you want to know the text of a menu item when it is clicked. To do that, you need to add an event handler onto the menu item. The following is clipped from the JavaDoc for ContextMenu:

MenuItem item1 = new MenuItem("About");
item1.setOnAction(new EventHandler<ActionEvent>() {
    public void handle(ActionEvent e) {
        System.out.println("About");
    }
});

You can get the event source, cast in to MenuItem and then get the text from that.

There's a real problem with your code the way it's written, though. You have calls to an external database in getTemplates, and as it's implemented as an @FXML element that almost guarantees that it'll be run on the FXAT, which is really, really bad.

I'd refactor that so that the database access is in a Task, and then the MenuItem creation is a handler for the onSucceeded event of the Task. Then you need instantiate a ContextMenu and install the MenuItem's on it in that event handler.

The getTemplates() method should be called as the onAction event for the button.

0
10/20/2014 4:11:33 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon