seinecle
seinecle

Reputation: 10778

extend class in Java FX?

In many occasions JavaFX needs to be customized with classes that extend existing ones. I tried this approach, for example to add a method to the NumberAxis class that would enable the label of the axis to be rotated. But I got a "NumberAxis is declared final, can't be extended" compiler error. I wonder how people who extend classes do? Do they have access to the source code of javafx, modify it to make some classes not final, and recompile it? (sounds tricky! )

Upvotes: 3

Views: 1426

Answers (1)

jewelsea
jewelsea

Reputation: 159416

Making lots of classes final in the JavaFX framework was an intentional decision by the framework developers. To get a flavor of why it's done, see the Making Color Final proposal. That's just an example, there are other reasons. I think experience with subclassing in the Swing framework was that it caused errors and maintenance issues that the JavaFX designers wanted to avoid, so many things are made final.

There are other way to extend functionality than to directly subclass. Some alternatives for your rotation example:

  1. aggregation: include the NumberAxis as a member of new class (e.g. NumberAxisWithRotatableText) which adds an accessor to get the underlying NumberAxis node and a method to perform the rotation (e.g. via a lookup as explained below).
  2. composition: for example extend Pane, add a NumberAxis, disable the standard text drawing on the axis and add rotated labels yourself as needed.
  3. css stylesheet: for example use a selector to lookup the text in the NumberAxis and the -fx-rotate attribute to rotate it.
  4. node lookup: Use a node.lookup to get at the underlying text node, and apply the rotation via an API.
  5. skin: All controls have a skin class attached them, replace the default skin class with a custom one.
  6. subclass an alternate class: Subclass the abstract ValueAxis class rather than the final NumberAxis class.

Source code for JavaFX is available with build instructions. However, I don't recommend hacking a personal copy of the source code to remove final constructs unless you also submit it as an accepted patch to the JavaFX system so that you can be sure that your app won't break on a standard JavaFX install.

If you really think it is a good idea for a given class to be subclassable, then log a change request. Sometimes the JavaFX developers are overzealous and make stuff final which would be better not being final. NumberAxis perhaps falls into that category.

Upvotes: 5

Related Questions