Mixing JavaFX, HTML 5, and Bananas with the NetBeans Platform
Posted
by Geertjan
on Oracle Blogs
See other posts from Oracle Blogs
or by Geertjan
Published on Fri, 29 Jun 2012 23:02:56 +0000
Indexed on
2012/06/30
3:20 UTC
Read the original article
Hit count: 252
/NetBeans IDE
The banana in the image below can be dragged. Whenever the banana is dropped, the current date is added to the viewer:
What's interesting is that the banana, and the viewer that contains it, is defined in HTML 5, with the help of a JavaScript and CSS file. The HTML 5 file is embedded within the JavaFX browser, while the JavaFX browser is embedded within a NetBeans TopComponent class.
The only really interesting thing is how drop events of the banana, which is defined within JavaScript, are communicated back into the Java class.
Here's how, i.e., in the Java class, parse the HTML's DOM tree to locate the node of interest and then set a listener on it. (In this particular case, the event listener adds the current date to the InstanceContent which is in the Lookup.)
Here's the crucial bit of code:
WebView view = new WebView(); view.setMinSize(widthDouble, heightDouble); view.setPrefSize(widthDouble, heightDouble); final WebEngine webengine = view.getEngine(); URL url = getClass().getResource("home.html"); webengine.load(url.toExternalForm()); webengine.getLoadWorker().stateProperty().addListener( new ChangeListener() { @Override public void changed(ObservableValue ov, State oldState, State newState) { if (newState == State.SUCCEEDED) { Document document = (Document) webengine.executeScript("document"); EventTarget banana = (EventTarget) document.getElementById("banana"); banana.addEventListener("click", new MyEventListener(), true); } } });
It seems very weird to me that I need to specify "click" as a string. I actually wanted the drop event, but couldn't figure out what the arbitrary string was for that. Which is exactly why strings suck in this context.
Many thanks to Martin Kavuma from the Technical University of Eindhoven, who I met today and who inspired me to go down this interesting trail.
© Oracle Blogs or respective owner