Validation in java (javafx)

Validation is one thing that’s missing from the core javafx framework. To fill in this gap there is already a 3rd party validation library that’s present in controlsfx. However there’s one issue I have with it: it wasn’t created with FXML in mind. That’s not to say it isn’t a good library, it just misses this detail and for me this is a no go. Because of that I decided to create my own validation framework: FXValidation.

How it works

To show you how FXValidation works let’s start from the bottom up, by showing you an example of what an FXML file might look like when using this library. This is a simple example of a login screen where the user needs to enter both an user name and a password:

<Label>
  <text>User Name:</text>
</Label>
<TextField fx:id="userName" id="userName"></TextField>
<Label>
  <text>Password:</text>
</Label>
<PasswordField fx:id="password" id="password"></PasswordField>

<Button text="Submit" onAction="#submitPressed"></Button>

<fx:define>
  <RequiredField fx:id="requiredField1" >
    <srcControl>
      <fx:reference source="userName"></fx:reference>
    </srcControl>
  </RequiredField>
  <RequiredField fx:id="requiredField2" >
    <srcControl>
      <fx:reference source="password"></fx:reference>
    </srcControl>
  </RequiredField>
</fx:define>

<ErrorLabel message="Please enter your username">
  <validator>
    <fx:reference source="requiredField1"></fx:reference>
  </validator>
</ErrorLabel>
<ErrorLabel message="Please enter your password">
  <validator>
    <fx:reference source="requiredField2"></fx:reference>
  </validator>
</ErrorLabel> 

On the beginning of the FXML snippet I define a textfield and password field for entering the login details. Other than that there’s also a submit button so the user may send the login information to the system. After that comes the interesting part. First we define a couple of validators of type RequiredField. This validators, check whether the input in question is empty and if so they store that the validation has errors in a flag. There’s also other types of validators built-in the FXValidation framework but we’ll get to that in a bit. Finally we define a couple of ErrorLabels. This are nodes that implement IValidationDisplay, any class that implements this interface is a class whose purpose is to display information to the user whenever there is an error in the validation process. Currently there is only one of this classes in the framework: the ErrorLabel. Finally we need to call validation when the user clicks the submit button, this is done in the controller on the submit method:

public void submitPressed(ActionEvent actionEvent) {
  requiredField1.eval();
  requiredField2.eval();
}

This will trigger validation for the validators that we have defined. If there are errors the ErrorLabels will display the error message that was defined in them. There’s also one extra thing the validators do: they add in the css style class of “error” to every control that is in error after the validation process has taken effect. This allows the programmer to style the controls differently using css whenever this controls have the error class appended to them. The programmer can check for errors in the validation process by checking the property hasErrors in the validators.

And here’s our example in action:

validation

The details

From what I’ve shown you above we can see that there are basically 2 types of classes involved:

  • The validator: takes care of checking if the target control (srcControl) conforms to the validation rule. If not it appends the “error” style class to target control sets its hasErrors property to true. All validators extend from ValidatorBase.
  • The error display information: this takes care of informing the user what went wrong with the validation, it might be that the field is required, the fields content doesn’t have the necessary number of characters, etc. All this classes implement IValidationDisplay.

In the library there are currenctly 3 validators and only one error “displayer” which is ErrorLabel. The validators are the following:

  • RequiredField: Checks whether the target control (srcControl) has content, if it doesn’t it gives an error.
  • CardinalityValidator: Checks whether the target control (srcControl) has at least a min number of characters and a maximum of max number of characters.
  • RegexValidator: Checks the content of the target control (srcControl) against a given regular expression

And that’s it.

I’d love to collaborate with ControlsFX or if someone else wants to contribute fell free to do so. So that we can achieve the definitive validation framework.

Toggle Switch for java

Background

A Toggle Switch is a control that is very popular, especially on touch based devices. You can see it in Android:

switches_switches

In iOS (6 and 7):

ios-7-toggle-switch1

And in Windows 8:

toggle-sync-setting-in-windows8

Functionally it works just like a check-box but for touch devices it has one big advantage: when your finger is over the touch device it won’t obscure the control and so you can see an instant feedback when you press it. The disadvantage is obviously that this control takes up more space.

Implementation

My implementation of the Toggle Switch allows you to change the text for the on and off state that appears right next to the toggle switch. You can also style the control using just CSS. It comes with a CSS implementation that gives it a metro look.

Demo

Below you can see a live demonstration of the control, in a light and a dark theme.

ToggleSwitch_LightTheme.gif

Toggle Switch (JMetro Light Theme)

Toggle Switch (JMetro Dark Theme)

Toggle Switch (JMetro Dark Theme)

 

You can grab the control and the accompanying metro style CSS by going to the jfxtras repository.

Further Developments

Currently it’s still not possible to style the Toggle Switch to look like the Android toggle switch using just CSS because it’s not possible to specify that the on and off text should appear inside the control and not outside as in the case of Metro. I’d also like to add the possibility to turn the animation on or off through CSS.

Metro style Slider for java (JMetro)

One thing that’s missing from java 8 javafx slider is the fill that comes from the beginning of the slider to the thumb. You can see this in windows 8 as well as several other operating systems: ios 6 and 7, android, etc.

So by using only CSS, it is not possible to style the fill of the slider, to accomplish this you’d have to create your own skin to use with the slider. And that’s exactly what I did by creating the “FilledSliderSkin”.

With this skin set on the slider you can style its fill color, like so:

.slider .fill {
 -fx-background-color: #00828b;
 -fx-padding: 0.333333em; 
}
.slider .fill:hover {
 -fx-background-color: #219297;
}

You can use this skin to achieve the styles of ios 6, 7 and android sliders.

And here are the screenshots of the slider with a metro style:

Slider - Dark Theme

Slider – Dark Theme

Slider - Light Theme

Slider – Light Theme

Metro style ProgressBar for java (JMetro)

It’s been a while since my last post..

I’ve been doing some tweaks here and there but nothing too significant for a blog post. Unfortunately haven’t had much time to spend on side projects, hopefully I’ll have time to style a new control every other week or so..

So, this time it’s the ProgressBar (also some other tweaks to the existing styles). Enjoy!

ProgressBar (dark theme)

ProgressBar – Dark Theme

ProgressBar (light theme)

ProgressBar – Light Theme

 

 

 

Metro style Password Box for java (JMetro)

The metro style password field is very similar to the Text Box (Text Input Field) in its design. The look is very similar and it also has a button to the far right of the control.

passwordBoxWindows8

Password Box with the password masked

 

This time instead of clearing the field, pressing the button will reveal the text you’ve just entered which is by default masked. This is useful, especially for long passwords and while entering the password through touch instead of a keyboard, which is less error prone.

passwordBoxWindows8-buttonPressed

Password Box with the password revealed

 

So here are the screenshots of the light and dark theme of the Password Box JMetro skin implementation:

Password Box - Light theme

Password Box – Light theme

Password Box - Dark theme

Password Box – Dark theme

Skinning in Java8 (JavaFX8)

There has been some changes in JavaFX8 regarding skinning, the most relevants of which are the new CSS API that allows you to create new CSS properties and pseudo-classes for your controls and the Skin class which has become public.

Using CSS you can change a lot of the appearance of a control, but there is only so much you can achieve with CSS and this is where the Skin class comes in. A quick look at the architecture of controls from “UI Controls Architecture”:

Controls follow the classic MVC design pattern. The Control is the “model”. It contains both the state and the functions which manipulate that state. The Control class itself does not know how it is rendered or what the user interaction is. These tasks are delegated to the Skin (“view”), which may internally separate out the view and controller functionality into separate classes, although at present there is no public API for the “controller” aspect. mvc

Like was mentioned there is still some aspects of Skinning that are not yet public API and that is the Behavior class, however, with the current state of things, you can already do a lot.

Since Java8 is not in G.A. status (full finished version) yet, there is still a considerable lack of documentation regarding the API, which brings me to my latest post on JMetro, at that time I was mistakenly under the impression that you had to extend a control in order to change its reference to the skin class, that’s why I created the ErasableTextField. However, as I later learned, you can change the skin class of a control just through CSS, like this:

.text-field{
    -fx-skin: "jfxtras.styles.jmetro8.MetroTextFieldSkin";
}

The “text-field” style class is assigned to TextField, so when the “-fx-skin” CSS property value is changed the reference to the skin class that is to be used with this control changes. So the ErasableTextField class is no longer necessary and has been removed from JMetro.

I find this design very interesting! As you can see the Skins are completely decoupled from the controls, all you have to do is assign a stylesheet to a scene without touching any of the code in your app and the look and feel of your application can change radically – like for instance JMetro Textfield skin adds a clear button that shows up whenever there is text inside:

jmetro-textbox

JMetro adds a clear button to TextField

DateAxis and XYBarChart update

Just the other day Gerrit Grunwald (@hansolo_) tweeted he made a DateAxis which supports JSR310 (date/time) api, and which is based on my work and also on Christian Schudt and Diego Cirujano-Cuesta work (they created a DateAxis which accepts DateTime). He later added that he would eventually create a blog post about it if he had time (you should stay tuned his posts are usually high quality). This reminded me that a blog post about my DateAxis and XYBarChart is long overdue since I’ve made a lot of changes since my last posts on the subject. Besides the changes I also wanted to explain my implementation of the DateAxis and why I’m sticking with the design (code design not artistic design) choices I’ve made.

Design decisions while creating DateAxis

While creating DateAxis I had two choices, either extend from Axis or from ValueAxis. Extending from Axis would allow me to accept DateTime or the new date formats from JSR310, while extending from ValueAxis would guarantee the presence of methods like setLowerBound and setUpperBound which would allow a user to filter or zoom in on specific dates, a fairly common use case, but would mean programmers would first need to convert the date to a number before adding it to the chart. Of course you can add filtering methods yourself while extending from Axis but a component that does zooming on charts and is expecting a ValueAxis (which guarantees setUpperBound and setLowerBound) wouldn’t work with that implementation.

Even though at first I was thinking that extending from Axis would be better, I’m now more convinced that the current solution – extending from ValueAxis, is a better one, for the reasons expressed earlier, and the draw back of having to convert the date to a number isn’t such a big thing.

I think it would be best if the JavaFX charts API would allow one to separate the position of a value in an axis from the value itself I think it would be best for setLowerBound and setUpperBound to be mandatory methods on Axis, but has things are right now you have to take in consideration the two drawbacks mentioned earlier before starting to implement a new axis.

Changes made to DateAxis and XYBarChart

I’m afraid I’ve probably forgotten about most of the changes I’ve made, anyway here’s what I recall:

DateAxis

  1. After changing range (by zooming in for instance) the tick marks interval stayed the same. Now they are recalculated.
  2. Added a bigger set of tick ranges to accommodate a higher range of dates.

XYBarChart (this previous post explains what this is)

  1. On some occasions depending on the data you add to the chart, it may not render any bars even though there is data to be displayed. This is a bug that exists in javafx BarChart and was passed on to this chart since there was some copying of code.

Today, I also added one more enhancement to the DateAxis which was on the pipeline of changes I wanted to make. Basically the format of the dates will change depending on the range of values that is being shown: for instance, if each tick mark represents more than a month than only the month and year of that tick mark is shown otherwise the day, month and year is displayed. A similar thing happens if the range of tick marks is bigger than one year, in that case only the corresponding year is shown. The following pictures show the before and after this change.

beforeChange8

XYBarChart with a DateAxis – before change

afterChange8

XYBarChart with a DateAxis – after change

This is just a small detail that makes for an easier scanning of the chart by the user.

If you want to join me, in adding more features to the charts API, you are welcome. My eventual objective would be for this to be integrated in the JavaFX API (at least the DateAxis) although I don’t know if that would be possible.

Metro style Text Box control for java (JMetro)

The Metro Text Box control is the usual input text field from which developers can get text input from users. This control has a particular trait usually present in control library designed to be used through touch: whenever the user enters text a clear button appears on the right most position of the control.

metroTextBox

Windows 8 Text input control

 

This particular feature isn’t available in the text input control from the JavaFX library, so the use of CSS won’t be enough to achieve a “metro” style.

For this reason I’ve created a new control: ErasableTextField (Yes, I know, not the best choice of a name for a control :-) ), which extends from TextField and adds this missing feature: a button which appears inside the text input control to clear it whenever there is text inside. Then through the usual use of CSS I style the control to make it look like the Windows 8 Text Box.

JMetro TextBox Dark theme - mouse pressed

JMetro Dark Theme – mouse pressed

JMetro TextBox Dark theme

JMetro Dark Theme

JMetro TextBox Light Theme - text selected

JMetro Light Theme – text highlighted

JMetro TextBox Light theme

JMetro TextBox Light Theme

Metro style Rating control for java (JMetro)

The Rating control is one of Windows first class citizens, it’s available in its control library, it allows a user to rate something from 0 to an x value. Given the importance of today’s social interaction it’s no wonder it has gained the status of a library control.

ControlsFX is a third party library of controls for JavaFX, it complements the standard library with some more useful controls and functionality which are not available straight from JavaFX’s standard library. One of the controls present is the Rating control which I opportunely took the chance to use and style the metro way through CSS.

Rating control

The Rating control (default style)

In its default style, this control uses raster image files. One for the “selected” state:

selected-star

and one for the “unselected” state:

unselected-star

Using this CSS code for the “unselected” state:

.rating > .container > .button {
  -fx-background-image: url("unselected-star.png");
}

And this for the “selected” state:

.rating > .container > .button.strong {
  -fx-background-image: url("selected-star.png");
}

“.strong” is the style class given to “selected” star buttons.

For JMetro I wanted to use vector based images instead of raster ones. To that effect I used the CSS property: “-fx-shape” and set the “-fx-background-image” to null which is the same as removing it.

Rating - Dark theme (mouse pressed)

Rating control – Dark theme (mouse pressed)

Rating - Dark theme

Rating Control – Dark theme

Rating - Light theme (mouse pressed)

Rating control – Light theme (mouse pressed)

Rating - Light theme

Rating control – Light theme

Advantages of using vector based images:

  • You can make them as big as you want without losing image quality
  • Fill color, stroke color, etc can be tweaked through CSS
  • It occupies less space

By this, I’m not saying that vector based images should be used every time, there are certainly use cases where raster based ones are more convenient, specially at lower sizes.

In conclusion, you can do some really powerful stuff this way using only JavaFX CSS code. You can either rely on the usage of raster based images or vector based ones.

Metro style ComboBox for Java (JMetro)

I’ll start this post by clarifying the purpose of this project. This project aims to provide skins for Javafx controls that are inspired by Metro style in Windows 8. The light theme tries to match as closely as possible the Windows 8 look while the dark theme which is not available on windows 8 is inspired by the metro look and provides a dark version.

There are some controls that exist in JavaFX but do not exist on Windows 8, for those controls I’ll try to reproduce a version that I think matches as closely as possible the Metro guidelines.

Finally, I’ve added one more style to the list of available controls: the ComboBox. Like I said before the light theme for this control tries to match as closely as possible the available version that exists on Windows 8, while the dark theme is a fresh new style inspired by the same Windows 8 control.

metro style combobox (dark theme)

Metro style ComboBox (Dark Theme)

metro style combobox (dark theme) 2

Metro style ComboBox (Dark Theme)

metro style combobox (light theme)

Metro style ComboBox (Light Theme)

metro style combobox (light theme) 2

Metro style ComboBox (Light Theme)

Metro style Tooltip for Java (JMetro)

This time a new control that was not present on the JMetro for javafx2.

The Tooltip:

tooltip jmetro

The style is the same for the dark and light versions of jmetro. With javafx 2 it was not possible to style a Tooltip like this because it had a page corner like effect that wasn’t possible to remove.

Metro style Push Button for Java (JMetro) – Revisited

This time the Push Button.

Tweaks:

  • Changed spacing between points on the focus ring (in accordance with what was done in the previous controls)
  • The button grew when it had focus in the light theme, this was fixed.
pushButton lightTheme1

Push Button Light Theme

pushButton lightTheme(button pressed)

Push Button Light Theme (button pressed)

pushButton darkTheme1

Push Button Dark Theme

pushButton darkTheme(button pressed)

Push Button Dark Theme (button pressed)

I’ve also fixed several issues with the CheckBox styling. Below you can see the CheckBox with jmetro Dark Theme (which I didn’t show before in the CheckBox post).

checkbox darktheme

CheckBox Dark Theme

Finally I’ve created a new project under the directory jmetro8. Stylesheets that work someway on java8 will work differently on javafx2, so because of this the folder jmetro will have the old stylesheets targeted at javafx2 and the folder jmetro8 will have the new stylesheets (the ones mentioned in my earlier posts) targeted at java8.

Metro style Context Menu for java (JMetro) Revisited

New update to JMetro. With tweaks to the old version and also tested and run under Java 8.

Tweaks:

  • size of menu items is bigger
  • padding around menu items is bigger
  • line separator width changed resulting in more clear line
  • padding around line separator is bigger
  • line separator aligned with menu item labels
contextMenuLight1

Context Menu light theme

contextMenuLight2

Context Menu Light Theme – mouse pressed

contextMenuDark1

Context Menu Dark Theme

contextMenuDark2

Context Menu Dark Theme – mouse pressed

Metro style Check Box for Java (JMetro) – Revisited

Last post I made about JMetro – my metro inspired skin (or look and feel) for Java, was about skinnng the calendar picker control. I was going to use Tom Eugelink nice calendar picker but I learned at that time that one was being created by Oracle and shipping with Java 8, so in the interest of time (have little spare time to waste) I thought it would be better to wait till Java 8 was more mature and continue my work on JMetro than, and skin Oracle’s official date picker instead.

So recently I restarted my work on JMetro by re-evaluating it and re-tweaking things where I think they need to be improved. Also I want to make sure that everything is working fine with Java 8.

Today I present a retweaked version of the checkbox control:

jmetro checkbox (before)

Before

jmetro checkbox (after)

After

The differences are on the checkbox mark (very slight difference) and on the focus ring, that is the dotted square you can see on the first checkbox indicating that it has focus.

I’m still not happy with how the fonts are being rendered, I’ll be investigating the reasons why fonts are being rendered poorly in the time I’ve left.

As usual, you can grab the code in the jfxtras repository .

What’s new in Java 8 (Part II – What might come)

Disclaimer: I do not work for Oracle or represent Oracle in any way. This list of features is not official. This is just part of my research as an “outsider”.

This is part II of a three part series of posts. In the first part, I talked about what Oracle has officially let developers know what should come out in JavaFX 8 (JavaFX is the new UI library for Java), I have been updating that article with new information that I come across.

In this second part I’ll talk about what might be coming in this Java8 release or a release some time after.

What might come

Support for ios and android

Official support for ios and android might be on its way. There is already a non Oracle effort to bring ios and android support to JavaFX called RoboVM, however it is still in its alpha stage and has a long way to become a fully formed commercially viable solution.

Oracle has not yet made any statement that it will officially support this platforms, yet there are some indications that this is already happening. Just look at these sessions on this years JavaOne from Oracle staff members, that @tobibertoni (twitter user name) has mentioned:

Build and Debug Your JavaFX Application for the iPad [BOF5517]

* David Pulkrábek – Senior Software Developer, Oracle
* Oldřich Matička, Oracle

JavaFX for iOS has begun to move to open source. In this session, you will see how to turn your JavaFX NetBeans project into a real iPad application. You will also be shown how to debug a JavaFX application on your device by using the Java Platform Debugger Architecture (JPDA) and step-by-step instructions for adding custom Java Native Interface (JNI) code to an iOS application.

https://oracleus.activeevents.com/2013/connect/sessionDetail.ww?SESSION_ID=5517

JavaFX on Android: First Insight [BOF7791]

* Tomáš Brandalík, Oracle

The gap between desktop and embedded has been filled with JavaFX on Android and iOS. JavaFX running on Android enables you to connect with tens of million of devices. This session gives you everything you need in order to successfully develop JavaFX applications on Android. First, it walks you through the complete development process, from project setup to debugging. Second, it explains the main building blocks: packaging, installation, the application lifecycle, fonts, interaction with device and operation system services, media, and WebView. Finally, it wraps up with the build structure and how developers can control and customize their own builds.

https://oracleus.activeevents.com/2013/connect/sessionDetail.ww?SESSION_ID=7791

High-Performance Java Applications Without Dynamic Code: Ahead-of-Time Code Generators for iOS [BOF4099]

* Robert Vandette – Consulting Engineer, Oracle

The Apple iOS and Android operating systems used in popular mobile devices are high-volume platforms that until now have lacked compliant Java support. This session describes Oracle’s plans to bring the latest Java language and API features from Java SE 8 to the Oracle ADF Mobile feature of Oracle Application Development System (Oracle ADF) for iOS and Android application development. It also discusses the features contained in the JDK 8 for Oracle ADF Mobile implementation and how to develop Java applications that target iOS and Android.

https://oracleus.activeevents.com/2013/connect/sessionDetail.ww?SESSION_ID=3783

JavaFX on the Web

Oracle is working on making it possible to run JavaFX on the web without any need for plug-ins (which are now being prohibited from use on several platforms). You can already check Bck2Brwsr, now on its 0.7.2 version.

Another idea is WebFX a specialized browser which can consume FXML directly.

Spice Up Your Browser with JavaFX [BOF7830]

* David Pulkrábek – Senior Software Developer, Oracle
* Oldřich Matička, Oracle

JavaFX is a powerful multiplatform graphics technology, but is it possible to run your JavaFX application in a browser without a plug-in? Directly from class files? Of course, it is! This session demonstrates a plug-in-free solution that brings JavaFX to your browser.

https://oracleus.activeevents.com/2013/connect/sessionDetail.ww?SESSION_ID=7830

The Chuck Norris Experiment: Running Java in Any Browser Without a Plug-in [CON4044]

* Jaroslav Tulach – NetBeans Platform Architect, Oracle
* Anton Epple – Trainer and Consultant, Eppleton
“Chuck Norris can run Java in any browser—without a plugin”. Find out what you need in order to reproduce Chuck’s roundhouse kick. In this session, you’ll learn everything you need in order to get started with “bck2brwsr”, a new open source project. Besides in GWT, the bytecode isn’t compiled to JavaScript but runs in a JavaScript-based JVM. The session shows you how simple it is to extend the capabilities of this project by creating your own APIs, which enables you to create maintainable applications by using, instead of JavaScript, a statically typed language with excellent tool support that runs in any modern browser. You’ll see a demo of building a Space Invaders–type game that runs on the iPad as well as Android devices. This is not a preview; you can use it today.

https://oracleus.activeevents.com/2013/connect/sessionDetail.ww?SESSION_ID=4044

WebFX: Running JavaFX Like HTML5 Apps [BOF3132]

* Bruno Borges – Principal Product Manager, Oracle

JavaFX for desktop applications is becoming a common case. But what if JavaFX could really replace HTML (or the new HTML5)? You’d simply go to a URL and load a Website built entirely with JavaFX. Support for CSS and JavaScript would already be included, and integration with servers using WebSocket or JAX-RS RESTful services would also be supported. Pressing refresh would be an easy way to reload the application (or should we say page?) and test the new version. Could FXPs, or FX Pages, really replace HTML5? This session takes a look and considers a new approach for Web 3.0.

https://oracleus.activeevents.com/2013/connect/sessionDetail.ww?SESSION_ID=3132

XYBarChart for javafx

One new addition to the FXCharts repo that I’ve created on github. This time it’s a XYBarChart, that is a bar chart that doesn’t have the limitation of the SDK BarChart which only allows you to have a CategoryAxis/ValueAxis pair of axes.So in other words, for example,  you can’t set a pair of axes if their of type DateAxis/ValueAxis. And as another consequence of these you can’t easily add zoom capabilities to a BarChart.

These type of chart wasn’t so easy to create was one might initially expect. Copy pasting the code from BarChart and altering the significant bits is not enough since BarChart relies on several package private methods from XYChart.

You can grab it from: https://github.com/dukke/FXCharts. If you have patches, features, fixes for this library please participate. Let’s create a better charts API.

 

DateAxis for javafx

A somewhat common request for people working with the charts API in JavaFX is a DateAxis. Essentially that would be an Axis that would be able to show dates.

I’ve hacked up a quick implementation of one, you can get it from github: https://github.com/dukke/FXCharts

It takes the time value of dates and displays them using the format given defined by “TICK_UNIT_FORMATTER_DEFAULTS”.

It’s not really a very elegant solution but it works. I’ll try to give a hand to Diego Cirujano-Cuesta and Christian Schudt who are working in a more evolved DateAxis that takes up Dates instead of their time value.

This implementation was done under Java8. It might work with JavaFX 2.2, I don’t know.

What’s new in Java 8 (Part I – JavaFX)

Disclaimer: I do not work for Oracle or represent Oracle in any way. This list of features is not official. This is just part of my research as an “outsider”.

Java 8 has become feature complete about two months ago and the developer preview is just around the corner (in a couple week’s time). This blog post will detail what’s coming in this next major release with an emphasis on JavaFX 8, which is the UI library. JavaFX release number is now on par with the Java release, that’s why it has jumped from 2.2 to 8.

This is part I of a three part series of posts. This first part will focus on what Oracle has officially been telling developers that should come out in JavaFX 8, the second part will be mostly speculative, and listing what I think might come out and is not officially being reported.  And the final part focuses on the rest that’s coming to Java 8, excluding the UI library (e.g., new language features and such).

Release dates

The original schedule aimed to ship the release in early September 2013, but due to the recent focus on browser-related security issues that date was not achieved. The new schedule is as follows:

  • 2013/06/13 – Feature Complete

All features have been implemented and integrated into the master forest, together with unit tests.

  • 2013/09/05 – Developer Preview

A reasonably stable build suitable for broad testing by the developer community is published. This build will include all planned features unless otherwise stated.

  • 2014/01/23 – Final Release Candidate

The date by which the final release candidate must be declared and submitted for testing. One or more release candidates will be declared after the planned ZBB date; if another is necessary after this milestone then the General Availability  date will be at risk.

  • 2014/03/18 – General Availability

Final release, ready for production use.

To this let me add that I’ve been developing Java based apps under Java 8 for more than a month now and consider it to be quite stable. I’m also not using any of the features under development (like 3D graphics for example), so I can’t say anything for that part.

You can already get an early access release of JDK8 here: http://jdk8.java.net/download.html

On that site you can also download some sample apps, where you can get a glimpse of what’s already possible to do.Ensemble8

New Features

The following list will focus especially on the most relevant upcoming features. The list of all coming new features and changes to existing ones is particularly big in this release and it could be that some relevant ones might have escaped my attention and may not me mentioned.

Rich text support

rich textRich text support will be added in JavaFX 8 via TextFlow class.

This will allow you to:

  • Style individual words;
  • apply effects to words
  • apply transforms
  • embed nodes inside text
  • support Bidi text, that is text containing text in both text directionalities, both right-to-left (RTL) and left-to-right (LTR)
  • create text that can be individually styled via CSS

For more details visit this links:

  • Rich text API Details:

  https://wikis.oracle.com/display/OpenJDK/Rich+Text+API+Details

Swing Node

Swing node will allow you to embed swing components inside a javafx scene. Support for the opposite, that is, embedding a javafx scene inside a swing app is already possible via JFXPanel.

For the API specification and a simple example visit: http://download.java.net/jdk8/jfxdocs/javafx/embed/swing/SwingNode.html

Changes to the controls API

Several changes will occur to the controls API, this is especially important to third party control providers:

  • Skin class which will become public;

SkinBase class will become public, but Behavior class and subclasses are still private implementation, there is still some work to be done here after JavaFX 8.

Video and audio recording

Support for video and audio recording will be added.

You can watch this video presentation for more details (jump to minute 39 to see an example app in action): http://www.youtube.com/watch?v=jaPUbzfJx2A

Update: Unfortunately this won’t be available after all. It has been postpone to a later release, code named “Van Ness” – https://javafx-jira.kenai.com/browse/RT-3458

Printing support

Printing support will be added to JavaFX. You can check this detailed blog post by Carl Dea for more details: http://carlfx.wordpress.com/2013/07/15/introduction-by-example-javafx-8-printing/

New looks with a new theme called Modena

Modena

The looks have been significantly improved with a new theme called Modena. This time a lot developer feedback was taken into account making for a very nice end result.

More details can be found here:

http://fxexperience.com/2013/03/modena-theme-update/

New DatePicker and TreeTable controls

JavaFX 8 will have a DatePicker and a TreeTable control:

  • DatePicker

DatePicker UXUser experience documentation: http://openjdk.java.net/projects/openjfx/ux/datePicker/

Actual DatePicker screenshot:

datePicker screenshot

Update: Jim Weaver has written about the DatePicker control, you can find his post here – http://learnjavafx.typepad.com/weblog/2013/08/quick-and-dirty-javafx-8-datepicker-example.html

  • TreeTable

TreeTableView

API examples: https://wikis.oracle.com/display/OpenJDK/TreeTableView+API+Examples

User Experience documentation:

https://wikis.oracle.com/display/OpenJDK/TreeTableView+User+Experience+Documentation

WebView Enhancements

The following enhancements were added to WebView:

  • Nashorn JavaScript engine (Update: I didn’t mean to say Nashorn is going to be webview Javascript engine. I’m just saying Nashorn will be available for use in Java8)

Nashorn’s goal is to implement a lightweight high-performance JavaScript runtime in Java with a native JVM. This Project intends to enable Java developers embedding of JavaScript in Java applications and to develop free standing JavaScript applications. (More on this on a later post).

More information on:

https://oracleus.activeevents.com/connect/sessionDetail.ww?SESSION_ID=4082&tclass=popup

Embedded Support

JavaFX will be included in Oracle’s Java SE Embedded 8. It will include a subset of features of the desktop version, namely it will not include:

  • WebView support
  • Media support

Workaround for media:

For media there is a workaround however, as this comment in FXExperience from Jasper Potts explains:

“There is no JavaFX media support on Pi, we prototyped passing
hardware decoded frames of video into OpenGL so that it could be drawn
in JavaFX Scene but performance was not great. So what we do is draw
JavaFX with a transparent background just like a transparent window on
desktop. Then use the native omx media player to play video to a lower
layer under the JavaFX graphics. So basically standard hardware overlay
graphics. This works great on PI and there is only about a 10% drop in
JavaFX performance when playing a HD video stream underneath. So simple
animations we can get 50+ fps with video at same time.”

(source: http://fxexperience.com/2013/08/javafx-hd-menus-on-raspberrypi/)

Improved 3D support

Improved 3D support will be available in this release. Or it’s probably more accurate to say: true 3D support.

It is an optional feature, you can query the runtime to know whether it is available for the given platform. When JavaFX runs with software rendering this 3D features will not be available.

·     Movable cameras and SubScene

  • Camera is now a Node

Camera can be added to a scenegraph, its position and aim (or orientation) is set using standard transforms.

  • Addition of SubScene

Subscene is a special node that can be used to render part of a scene with a different camera.

·     3D primitives

  • Added two type of 3D shapes, extending from an abstract Shape3D base class:
    • User-defined shapes (MeshView)
    • Predefined shapes

Three commonly used predefined 3D shapes are introduced: Box, Cylinder and Sphere.

Shape3D class Hierarchy:

  • javafx.scene.Node
    • javafx.scene.shape.Shape3D (abstract)
      • javafx.scene.shape.MeshView
      • javafx.scene.shape.Box
      • javafx.scene.shape.Cylinder
      • javafx.scene.shape.Sphere

Mesh Class Hierarchy:

  • java.lang.Object
    • javafx.scene.shape.Mesh (abstract)
      • javafx.scene.shape.TriangleMesh

·     3D Attributes

  • Added lights and 3D materials to add realism for 3D shapes.

Material specifies the appearance of a 3D shape. Light interacts with the geometry of a Shape3D and its material to provide the rendering result.

A Shape 3D can be rendered either as a filled shape or as a wireframe.

·     Light

  • Light is defined as a node in the scene graph
  • There are 2 types of light sources:

AmbientLight: A light source that affects all objects equally. AmbientLight objects model the light reflected from other visual objects. If you look up at the underside of your desk, you will see the bottom surface of the desk although no light source is directly shining on that surface (unless you have a lamp under your desk). The light shining up on the bottom surface of the desk reflected off the floor and other objects. In natural environments with many objects, light reflects off many objects to provide ambient light. The AmbientLight class simulates this effect.

PointLight: A light source with a position. The distance and direction to a given object affects how this lights up the object. PointLight objects approximate bare light bulbs, candles, or other light sources without reflectors or lenses.

May add more types of lights in the future (example: spot light, a light that simulates light sources such as flash lights).

  • A scene contains a set of active lights

A default light is provided when the set of active light is empty

  • Each light contains a set of affected nodes

If a Parent is in the set, all its children are affected. The default is the root node of the Scene.

·     Material

  • Material contains a set of rendering properties
  • PhongMaterial is a concrete subclass of Material. It has the following properties:
    • Ambient color
    • Diffuse color, diffuse map
    • Specular color, specular map
    • Specular power
    • Bump map
    • Self-illumination map

·     Methods added to Node

  • A LOD helper method that returns the area of the Node projected onto the physical screen in pixel units:

public double computeAreaInScreen()

LOD stands for Level of Detail. It is technique that changes the appearance of an object depending on how close or distant to the camera it is, or in other words the level of detail is changed according to the area occupied by the object if the object is far then the detail can be lowered without the user noticing it, and thus improving performance.

  • A new set of methods that transform 3D points

·       Loader support

Many 3D file formats exist, such as:  Obj, Maya, 3D Studio Max, Collada, KRML. There will be no official 3D file format loaders shipping with the API. Oracle however will provide sample code for one or two popular formats. At least a Collada file loader is in the works.

References

Other minor features, tweaks and changes

Builders are deprecated

Builders are now deprecated in this release. In Java 9 they will be removed (this is several years down the road). You should start planning to replace builders if you are using them.

Reason:

Due to an implementation detail, Builders would stop working in Java 8 unless some binary incompatibilities were introduced. Because of that the decision was to phase out the Builders, the changes that were required would reduce the value of the builders to the point where they just wouldn’t be worth it, and when considering Mobile / Embedded use cases, the extra cost of the builders would be prohibitive. (http://mail.openjdk.java.net/pipermail/openjfx-dev/2013-March/006725.html)

Javafx thread and swing will merge

JavaFX thread and swing can be merged, this is still an experimental API and will not be public, and you’ll have to turn it on explicitly. If you are developing a hybrid Swing/JavaFX app this will simplify the code since you only have to worry about one UI thread.

You can read more about this in this blog post:

http://wiki.apidesign.org/wiki/JavaFX

JavaFX fully open sourced

JavaFX has just recently become fully open sourced. This is great news since it will allow third parties and developers to extend the functionality of JavaFX more easily and thoroughly. Also good for debugging errors, and other things.

JavaFX on the default classpath

This has been a recurring request from developers, JavaFX classes are now on the default runtime classpath for an Oracle Java implementation.

Swing JDesktopPane with scrollbars

JDesktopPane with scrollbars

For a long time there has been a known issue with Swing’s JDesktopPane. If a JInternalFrame gets out of the viewport, no scrollbars are added and you loose the ability to “reach” the JInternalFrame.

Recently I had to fix this for a project. I searched the web for a simple straight solution to this issue but couldn’t find one so I decided to put my hands on the problem and try to fix it.. I’ve come up with a solution and decided to share it on github.

All you have to do is simply pass a JDesktopPane to this component and add it to a app where you would add the JDesktopPane.

At the base of this problem is the fact that the JDesktopPane doesn’t update its preferred size when the JInternalFrames get out of the viewport. This component will keep track of the JInternalFrames position and add scrollbars when it’s appropriate.

You can grab the code at: https://github.com/dukke/swing-desktopScrollPane

Integrating JavaFX and Swing (Revised)

I’ve just finished rewriting a component of my app that was using Swing and now is using JavaFX, I’ve ended up with a JavaFX component that integrates with the larger swing app. It is a large app and the rewrite took me a while, in the end everything worked fine and I’m glad I did it.

Reasons you might want to do this in your swing app

You might want to rewrite your Swing app and change it to use JavaFX instead, the easiest way is to do this incrementally by changing each component at a time. This requires that you integrate each of the newly changed JavaFX components with the rest of your Swing app.

I’ll summarize why you might want to start rewriting your app from Swing to JavaFX:

  • It’s the future

Swing is pretty much dead in the sense that it won’t get any further developments. JavaFX is the new UI toolkit for Java, it is better prepared for the future with things like touch support, 3D, built-in animation support, video and audio playback, etc.

  • Probable future support for mobile: Android, IOS…

There is already a working prototype that enables you to port javafx apps to IOS called RoboVM – http://www.robovm.org/. As more and more of JavaFX gets open sourced the better RoboVM will get, with this open sourcing probably other utilities will arise that will enable ports to other environments.

  • It’s solid

JavaFX is a well-designed toolkit with a rapid growing pace, a bright future and a set of good free UI tools. Furthermore, unlike in the past, Oracle is giving developers feedback a great importance changing and adapting its APIs to meet their goals.

  • It’s pretty

Unlike Swing, not counting third party librarys, which was ugly by itself, JavaFX looks good right from the start, especially the new Modena skin coming to JavaFX 8: http://fxexperience.com/2013/03/modena-theme-update/- . Given that users nowadays expect good looking, well designed apps this is a pretty good point.

  • Nice extras

Some nice extras, like the charts API, an embedded browser that supports HTML5, etc.

How you do it

Back on JavaFX 1.3 you could embed Swing in JavaFX but not the other way around, at least not officially. I implemented a Swing component that allowed you to embed JavaFX content in Swing (called JXScene) and made it publicly available in the jfxtras project. It was the only way you could embed a JavaFX scene in a Swing app.

Now Oracle with JavaFX 2.X made an official way of embedding JavaFX in Swing which makes more sense but unfortunately not a way to embed Swing in JavaFX, I guess this will suffice in most cases. However, with the coming JavaFX 8 you’ll also have the ability to embed a swing component in a JavaFX app with the Swing Node.

ARQUITECTURE

Essentially when you are embedding JavaFX in Swing you end up with 2 running UI threads: the Swing EDT thread and the JavaFX User thread.

There is a chance that in the future there will only be one thread for both as is the case with SWT, making Swing run on the JavaFX User Thread, but for now we’ll have to manage our way with 2 threads.

Two threads running at the same time in the UI is what complicates matters, and makes JavaFX integration not as easy as you might expect, unless you’re doing some trivial small app but I guess that is not the scenario for most of the real world use cases. If you’re doing a small app might as well do it all in JavaFX.

CODING

JavaFX gives you JFXPanel, which is a Swing panel that hosts a JavaFX scene. You set the scene on the JFXPanel and add the panel wherever you could add a Swing Component.

To access JavaFX data you have to wrap your code in a Runnable object and call the Platform.runLater method:

jbutton.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
        Platform.runLater(new Runnable() { 
            @Override
            public void run() {
                fxlabel.setText("Swing button clicked!"); 
            }
        });
    }

});

On the other side is Swing data. This data must be accessed only by the EDT. To ensure that your code is running on the EDT, wrap it into a Runnable object and call the SwingUtilities.invokeLater:

SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
        //Code to change Swing data.
    }
});

Tips

  1. JavaFX already throws exceptions when you access a JavaFX resource outside the JavaFX User Thread, but bear in mind that this does not happen always. To minimize performance costs not all situations are checked.
  2. If you use Substance (in my opinion without any doubt the best looking free look and feel for swing) third party library than an exception will also be thrown whenever a Swing resource is accessed outside the EDT. Setting Substance as your Swing look and feel might be a good solution to lessen concurrency mistakes on the swing side that you might do.
  3. Be very careful when sharing resources between the 2 UI threads, try to avoid this as much as possible. Best way to solve multi-threading problems is to avoid them, and these kind of problems are among the most difficult to solve in Software Engineering. There is a reason why Swing started off as a multi-threaded toolkit and ended changing to a single threaded one.
  4. Sometimes you might want to check if you are on the JavaFX User Thread via Platform.isFxApplicationThread() and only than issue a call to Platform.runLater(…), because if you are on the JavaFX User Thread and call runLater(...) the execution of the code that is inside will still be deferred to a later time and this might not be what you want.
  5. There are a lot of JavaFX controls that cover their swing counterpart, however they are different and have different features that you must adapt to. There are also some controls like the JFormattedTextField that don’t yet exist. In conclusion JavaFX is different from Swing. Has different controls and a different arquitecture and API that you must adapt to.
 Other links to check out:

Metro style Spinner for Java (JMetro)

Here is Tom Eugelink’s spinner control from JFxtras with a metro style.It’s basically a control that allows the user to iterate through a list of values using an increment and decrement button.

I’ve changed the code on ListSpinner so you’ll have to use my version in order for the metro style css to work.

A sample app is included in the files.

Java Calendar with a metro style

Following a discussion with Tom Eugelink author of a Calendar control for JavaFX I’ve decided to have a try at styling it with a Metro like style.

There is no Calendar control or spinner control, which is used in Toms Calendar, in the windows 8 (metro) toolkit of controls, so I had to come up with a fresh new design for this. Actually the ComboBox of Metro behaves a bit like the spinner control of ios but still it’s not like the spinner control of previous Windows versions where you have up and down (or left and right) arrows to slightly increment/decrement the values.

I also had touch in mind, so the increment/decrement buttons in the spinner are far apart enough to not be accidentally touched instead of the other increment/decrement button you aimed for.

The following picture shows the current wireframe for the Calendar control. It is a high fidelity wireframe so this is actually how the control will ultimately look like:

calendar

What do you think?

Metro style Toggle Button for Java (JMetro)

Toggle button metro style:

You can get it at the usual places.

JMetro has  been recently blatantly copied by someone else who has than tried to make  it look like it was his own work. JMetro is under BSD license as are other components/controls present in the JFxtras repository, BSD license legally requires you to give credit to the original owner of the work.

There is no problem in using the work on commercial/non-commercial projects and on creating derivative work as long as you give credit to the original creator. Since I’m giving away my work for free I think the least I can ask for is some credit.

Metro style Combo Box for Java (JMetro)

This update brings the ComboBox control to the JMetro library. The following pictures show the light and dark theme:

There is a slight miss placement of the popup. Which according to Jonathan Giles has been fixed on JavaFX 8.

Metro style Scroll Pane for Java (JMetro)

Just a small update based on the metro style I’ve created for the scroll bars, here’s the ScrollPane:

I’ve also uploaded the code to the jfxtras-styles repository, so you can now get it from there also.

Metro style Scroll Bar for Java (JMetro)

Here is the Scroll Bar control with a metro style (light and dark theme):

ScrollBarLightThemeScrollBarDarkTheme There is a bug on javafx that won’t allow to change the style of the thumb when it is pressed.

The css code to style the thumb on this state is present on the stylesheets so  the pressed state style of the thumb will become visible, whenever the bug disappears from the javafx runtime.

As a reminder, all you need to do to style your whole application with this metro style is to add the desired stylesheet (the dark or the light theme file) to the root node of the scene.

One thing that is on the to-do list for this project is changing the controls sizes to better accommodate touch. Some controls are too small right now for that.

On the future I’ll be adding this to the JFxtras repository so besides being able to get it from the usual place you’ll also be able to get it from there.

Metro style Context Menu for Java (JMetro)

Another update to JMetro: Context Menu with a metro style.

The dark and light theme both have the same styling on this control:

contextmenu metro

You can’t see the mouse pointer because this was screen captured. It’s over the “Highlight” label.

You can get this from the usual place: https://www.dropbox.com/sh/xvx1w4535x1mjm6/ntbCK7PP9z

If you dig into the css code you’ll see that there’s also a commented out implementation of the tooltip control. Unfortunately JavaFX CSS for this control is currently faulty, so we’ll have to wait for another release of JavaFX to fix this.

One last note: if you haven’t submitted the survey to put JavaFX on mobile and tables, please do so here: http://fxexperience.com/2012/12/javafx-for-tablets-mobile/ . It will take you less than 5min and can make the difference between it actually happening or not.

Metro style Check Box for Java (JMetro)

Here is an update to JMetro: the Checkbox with a metro style.

A picture of the demo app running with the light and dark metro theme:

The first button has the focus, that’s why it has a dashed square around it. I’ve also made changes to the push button. You can get everything from the same place.

I’ve also changed how you apply the theme. Now all you have to do is add the style sheet and buttons and checkboxs will change style automatically. That’s because now I’m overriding the default look of the controls so you don’t have to add style class’s to them.

The fonts aren’t still the same as in Metro, I’ll try to see if I can change that in a later iteration. Even if you test this on Windows 7, which also has Segoe UI, it will be different because Segoe UI on windows 8 is slightly different.

JMetro – Windows 8 Metro controls on Java

Hi,

I’ve been studying the interface of Windows 8, so I thought why not do a windows 8 theme for Java and what better timing that this given that there are only 3 days left for windows 8 to be available.

My first control is the Windows 8 “Push Button”, it’s simply just the normal button that you’re used to.

I’ll be releasing two themes: a dark theme (JMetroDarkTheme.css) and a light theme(JMetroLightTheme.css). The pictures below are just a still of the demo app, they do not illustrate all the states and corresponding styles the “Push Button”s can have.

Together with the css files I’ve put an fxml file as an example. You can open it in scene builder than choose the style sheet you want to use by pressing “Preview -> Preview a style sheet…”. To see it in action click “Preview->Preview in window”.

The buttons are simply styled by adding the “.push-button” css class to a Button.

You can get the files here. Use them for any purpose, commercial or not.

Zooming inside a Scrollpane

In JavaFX if you want the user to be able to zoom the contents inside a scrollpane here’s a small gotcha that you have to be aware of: to accomplish this you must wrap the contents of the scroll node inside a group so that the visual bounds (not the layout bounds) are used for layout calculations.

Scrolling can than be attained by setting a scaling transform on the contents of the Scrollpane and adjusting the scale value to meet the specified zoom level.

Here’s a small snippet of code to illustrate how you could do it:

public class ZoomableScrollPane extends ScrollPane{
  Group zoomGroup;
  Scale scaleTransform;
  Node content;
  (…)
  public ZoomableScrollPane(Node content)
  {
    this.content = content;
    Group contentGroup = new Group();
    zoomGroup = new Group();
    contentGroup.getChildren().add(zoomGroup);
    zoomGroup.getChildren().add(content);
    setContent(contentGroup);
    scaleTransform = new Scale(scaleValue, scaleValue, 0, 0);
    zoomGroup.getTransforms().add(scaleTransform);
    (…)
  }
  (…)
}

Style a stage in a minimalist way

There are various modes in which you can style a window in JavaFX. Sometimes it may be interesting to style it in a minimalist way without any window decorations but only the ones provided by the OS such as a drop shadow in Windows 7.

First lets take a look at what JavaFX gives you. There are 4 ways to style your Stage:

  • StageStyle.DECORATED – A stage with solid white background and platform decorations.

  • StageStyle.UNDECORATED – A stage with a solid white background and no decorations.

This is basically just a Stage with no decorations at all just a solid white rectangle with no borders  for you to paint on.

  • StageStyle.TRANSPARENT – A stage with a transparent background and no decorations.

Same as the above but with a transparent background instead of solid white.

  • StageStyle.UTILITY – A stage with a solid white background and minimal platform decorations.

This one is similar to the StageStyle.DECORATED expect that the corners aren’t round, there is no minimize and maximize button and the close button is smaller. Also it does not show up on the windows taskbar so it is not meant to be a top level application window but a secondary one.

So there is no provided way to style a top level window with only the OS decorations. To achieve this you’ll have to create a window with no decorations using StageStyle.UNDECORATED and style the top level container through CSS.

The following code sets the top level container borders as round and adds a drop shadow to achieve the windows 7 appearance:

-fx-background-radius: 6;

-fx-border-color: gray;

-fx-border-style: solid;

-fx-border-width: 1;

-fx-border-radius: 6;

-fx-background-radius: 6;

-fx-effect: dropshadow(three-pass-box, rgba(100, 100, 100, 1), 24, 0.5, 0, 0);

However, there is a problem with this code. The drop shadow will not be visible since it falls outside the bounds of the scene. For it to be visible you’ll have to provide some space around the top level container, you can do this using -fx-background-insets  which sets the insets of the container and -fx-border-insets which sets some space around the borders as well.

So the final CSS for a top level container with a style class of rootPane will look like this:

.rootPane

{

  -fx-border-insets: 23;

  -fx-background-insets: 23;

  -fx-background-radius: 6;

  -fx-border-radius: 6;

  -fx-border-color: gray;

  -fx-border-style: solid;

  -fx-border-width: 1;

  -fx-effect: dropshadow(three-pass-box, rgba(100, 100, 100, 1), 24, 0.5, 0, 0);

}

And the window will look like this:

(The logo, top header and close button are later additions, i.e. not a result of the CSS code above)

Target text on JavaFX UI controls through CSS

Here’s a small post on how you can target text on UI controls through CSS.

Just do this:

<control> .text
{
    /* CSS targeting the text in the UI control */
}

To change the text appearance on any of the JavaFX controls.

Example (adding a drop shadow to the text on a button):

.myButton .text {
    -fx-effect: dropshadow( one-pass-box , rgba(100, 100, 100, 0.5) , 0, 0.0 , 0 , 1 );
}

Result:

I think this is a very nice way to style text on UI controls, one which is not available on regular “Web HTML CSS”.

Circle buttons in css

This is just a small trick in css to create circle like buttons.
To achieve this just put the width and height equal to each other and equal to the css border radius of a button.
If the button is 20 by 20 px than to make it look like a circle in JavaFX CSS:

.circleButton
{
    -fx-border-radius: 20;
}

I believe this also applies to web CSS3 but I haven’t tested it.
The following picture illustrates a zoom panel that I’ve done. The two buttons for zoom in and zoom out look circle like.

 

Integrating JavaFX and Swing

I’ve just finished rewriting a component of my app that was using Swing and now is using JavaFX, I’ve ended up with a JavaFX component that integrates with the larger swing app. It is a large app and the rewrite took me a while, in the end everything worked fine and I’m glad I did it.

Reasons you might want to do this in your swing app

You might want to rewrite your Swing app and change it to use JavaFX instead, the easiest way is to do this incrementally by changing each component at a time. This requires that you integrate each of the newly changed JavaFX components with the rest of your Swing app.

I’ll summarize why you might want to start rewriting your app from Swing to JavaFX:

  • It’s the future

    Swing is pretty much dead in the sense that it won’t get any further developments. JavaFX is the new UI toolkit for Java, it is better prepared for the future with things like touch support, 3D, built-in animation support, video and audio playback, etc.

  • Probable future support for mobile: Android, IOS…

    From what I’ve been seeing, I think it’s pretty much a guarantee that Android, IOS, etc support will be made available, Oracle already has working prototypes of this that they show on public conferences, the only question is when. I think it won’t take that long, probably we’ll see more on this in the next JavaOne, coming up soon.

  • It’s solid

    JavaFX is a well-designed toolkit with a rapid growing pace, a bright future and a set of good free UI tools. Furthermore unlike in the past, Oracle is giving developers feedback a great importance changing and adapting its APIs to meet their goals.

  • It’s pretty

    Unlike Swing, not counting third party librarys, which was ugly by itself, JavaFX looks good right from the start. Given that users nowadays expect good looking well designed apps this is a pretty good point.

  • Nice extras

    Some nice extras, like the charts API, an embedded browser that supports HTML5, etc.

How you do it

Back on JavaFX 1.3 you could embed Swing in JavaFX but not the other way around, at least not officially. I implemented a Swing component that allowed you to embed JavaFX content in Swing (called JXScene) and made it publicly available in the jfxtras project. It was the only way you could embed a JavaFX scene in a Swing app.

Now Oracle with JavaFX 2.X made an official way of embedding JavaFX in Swing which makes more sense but unfortunately not a way to embed Swing in JavaFX, however I guess this will suffice in most cases.

Arquitecture

Essentially when you are embedding JavaFX in Swing you end up with 2 running UI threads: the Swing EDT thread and the JavaFX User thread.

There is a chance that in the future there will only be one thread for both as is the case with SWT, making Swing run on the JavaFX User Thread, but for now we’ll have to manage our way with 2 threads.

Two threads running at the same time in the UI is what complicates matters, and makes JavaFX integration not as easy as you might expect, unless you’re doing some trivial small app but I guess that is not the scenario for most of the real world use cases. If you’re doing a small app might as well do it all in JavaFX.

Coding

JavaFX gives you JFXPanel, which is a Swing panel that hosts a JavaFX scene. You set the scene on the JFXPanel and add the panel wherever you could add a Swing Component.

To access JavaFX data you have to wrap your code in a Runnable object and call the Platform.runLater method:

jbutton.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
        Platform.runLater(new Runnable() { 
            @Override
            public void run() {
                fxlabel.setText("Swing button clicked!"); 
            }
        });
    }

});

On the other side is Swing data. This data must be accessed only by the EDT. To ensure that your code is running on the EDT, wrap it into a Runnable object and call the SwingUtilities.invokeLater:

SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
        //Code to change Swing data.
    }
});

Tips

  1. JavaFX already throws exceptions when you access a JavaFX resource outside the JavaFX User Thread, but bear in mind that this does not happen always. To minimize performance costs not all situations are checked.
  2. If you use Substance third party library than an exception will also be thrown whenever a Swing resource is accessed outside the EDT. Setting Substance as your Swing look and feel might be a good solution to lessen concurrency mistakes on the swing side that you might do.
  3. Be very careful when sharing resources between the 2 UI threads, try to avoid this as much as possible. Best way to solve multi-threading problems is to avoid them, and these kind of problems are among the most difficult to solve in Software Engineering. There is a reason why Swing started off as a multi-threaded toolkit and ended changing to a single threaded one.
  4. Sometimes you might want to check if you are on the JavaFX User Thread via Platform.isFxApplicationThread() and only than issue a call to Platform.runLater(…), because if you are on the JavaFX User Thread and call runLater(...) the execution of the code that is inside will still be deferred to a later time and this might not be what you want.

Other links to check out:

Modellus X 0.1 Release Candidate

Finally, after months of my spare time that amount to years, I’m finally able to release a version of my hobby project Modellus X 0.1 that I consider suitable for public release. For those who do not know Modellus, it is a free software used mainly to help in the education of sciences. On a more technical level this is a Swing with embedded JavaFX app.

This is a release candidate meaning it is very near the final version, the only thing that is missing is translation to other languages (other than English(UK) and Portuguese(Portugal)) and this is where I would ask for your help, if you think you have the capability of translating to other languages/locales that are missing than please contact me, full credit will be given and the Modellus community will be very thankful to you. Also feedback and bug reports would be very helpful.

This version can load all models made on previous versions 4.01 and 4.5.

You can temporarily get it here: Modellus google code download page You can also get previous Modellus versions examples from there. I’m currently also finishing a new site (www.modellus.co) wish will better serve the community. It will be the future home for all things Modellus.

There will be Windows 32, windows 64, mac and linux releases of the final Modellus X 0.1.

Going forward I expect to make public releases more often, not more than a couple months or so.

I hope you enjoy using  it as much as I enjoyed developing it.

Modellus 5 beta – Selecting an image from disk for the particle

To keep users updated on the new features being added and upcoming on Modellus 5, I’ll be producing a series of videos and blog posts.

For the videos I’ve created a youtube channel: http://www.youtube.com/user/DuqueVieiraPedro and for the posts I’ll currently do them here but in the near future a new blog will be created which will be the focal point for all Modellus news, activities, community news, etc.

First up on this series is “selecting image from disk for the particle”, this new feature which should have probably be already included and will certainly come in handy, allows a user to select an arbitrary image from disk to represent the particle, the video of this feature is here: http://www.youtube.com/user/DuqueVieiraPedro?feature=mhee#p/a/u/0/pvCLszpKphg

I’ve been working hard on my spare time with the help of Albino Rafael (fisicanalixa.blogspot.com) which is doing all the user testing,  and hope to have a public release soon. Two more features and it will come out, these are controller pause/stop conditions (which I’ll start doing next) and video analysis.

First we’ll have a public preview release so translations to other languages may start and shortly after the Modellus 5 final release.