简体   繁体   中英

How to handle Javafx org.w3c.dom.Element cast to MenuItem error?

I'm having issues creating a context menu for a WebView.

private void createContextMenuForButton(){
    MenuItem clickButton = new MenuItem("Click");
    clickButton.setOnAction(new EventHandler<ActionEvent>(){
        public void handle(ActionEvent evt){
            addStep();
            ListItem item = ListItem.getListView().getItems().get(ListItem.getListView().getItems().size()-1);
            item.setComboBoxValue("Click");
            *String value = ((Element)evt.getTarget()).getAttribute("value").toString();*
            item.getWindow();
        }
    });
    listViewItemContextMenu.getItems().remove(0, listViewItemContextMenu.getItems().size());
    listViewItemContextMenu.getItems().add(clickButton);
}

When I run the method above I get the follow exception. Line 190 is marked with *. No matter how I try to get the elements of an ActionEvent it continue to get the error. I can't create an @FXML MenuItem because I need to be able to create new and different menuItem on the fly.

    Exception in thread "JavaFX Application Thread" java.lang.ClassCastException: javafx.scene.control.MenuItem cannot be cast to org.w3c.dom.Element
        at model.WebBrowser$4.handle(WebBrowser.java:190)
        at model.WebBrowser$4.handle(WebBrowser.java:1)
        at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
        at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
        at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
        at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
        at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)

From the exception, it looks like you are trying to cast a JavaFX MenuItem object to an Element type from the Java API for DOM from W3C. That doesn't make any sense. Doesn't it work without the cast, if what you are after is the value of the MenuItem ? Try casting it to MenuItem instead of Element .

edit:

Ok had a more close look at it. Looks like it should be something like this, if what you want is the text value of the property text :

String value = ((MenuItem)evt.getTarget()).getText();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM