As I am
working on a new MapViewer component for AgroSense (it is fork, but very modified, of abandoned project swingx-ws) I am facing
some strange behavior of JavaFX components, which I have never met in Swing.
It is a combination of StackPane, Canvas and painting images in the Canvas.
And what was the problem?
Having
Canvas in StackPane and some components, for example BorderPane with Buttons
and Slider, on top of it, components in upper layer of StackPane tend to disappear,
especially when moving mouse over other components. The component with focus or with mouse over it looks good, but other disapear.
As I was
searching for the root cause of trouble, I tested some combinations of painting in
Canvas (GraphicsContext.fillRect(), GraphicsContext.drawImage() etc.) and only
drawing of image was troubled. And when the Pane with components wasn’t over
the painted image, the problem was gone.
Searching for the problem
But how to
find out what is going wrong? When painting, debugger is useless and putting
System.out.println() to every suspicious method is lengthy and rarely give some
valuable results. I even experimented with styles and after removing all hover
behavior the problem was almost gone!
This really isn’t a solution, but can
lead you to the real cause of trouble. Now I know it is related with drawing
styles, maybe.
Read the Javadoc!
Honestly,
how many of you read Javadoc of every class, you intend to use? I know, it
depends :-) Starting with Canvas, there is a lot of reading, so I started from
the bottom with Node class. And there it was, almost at the beginning: the blendMode.
The Javadoc
for this field says:
The BlendMode used to blend
this individual node into the scene behind it. If this node happens to be a
Group then all of the children will be composited individually into a temporary
buffer using their own blend modes and then that temporary buffer will be
composited into the scene using the specified blend mode.
And the
BlendMode enum Javadoc:
A blending mode defines the manner in which the
inputs of a Blend effect are composited together or how a Node is blended into
the background of a scene.
Well, it
doesn’t look it should solve my problem, but looks interesting, so why not to give it a try. Not sure, which value of BlendMode enum to use, I decided to try one after
another.
I really, really recommend you to read Javadoc of this enum to really understand
which one to use. Different values give you very different results – yellow image,
negative image etc. it depends on the image and background of the scene.
My
winner is BlendMode.MULTIPLY.
This solved my problem, but now I have to find out why this special combination of components and settings behaves so strangely. But it will be topic for another story.
Conclusion
If you have
some issues with painting, check the BlendMode setting and try to read Javadoc
before you run in some trouble. It takes some time, but at the end of the day,
it can save you much more time and troubles.