søndag 28. oktober 2012

JavaFX WebView size trick


JavaFX comes with a web browser component called WebView. It is based on the open source WebKit browser, which bring tremendous power to Java.
But when you try to use it as a regular component like the Text and want to make it fit within the other components it can be quite a challenge to make it behave. Especially when you don't want to use it as a traditional "surfing the web" browser, but as a component to show more or less static HTML content.

Text will size out between min and max, and try to honor the preferred size and squeeze in where there is place. JavaFX will use its magic to make that happen. WebView is a shell that will kind of fit based on its parent, but the internal Webkit will size up based on its own calculation of the HTML/CSS/JS content, and a scrollbar will pop up when needed. The link between WebView and Webkit seems weird in light of how the rest of JavaFX works.

Lets make it behave, shall we?

JavaFX 2.x - Bindings and Properties


JavaFX comes with a couple of cool features which Swing doesn't have. Instead of using literals like int, double, string etc, JavaFX comes with properties. The content in a Textfield is found in the textProperty() which happen to be a StringProperty class. You can get the string, but you can also do binding or adding listeners.

This is a nice way of reducing boiler plate code, and it gives the opportunity for creative solutions.