JavaFX: Include common FXML file from common lib in current FXML - javafx

We have multiple GUI project based on JavaFX. Our goal now is to refactor a lot of these GUI's and to extract common views and source code and make this common code available through libs (bundle jar's). I currently have the problem that I have a View which displays log files and which is included via an FXML in the main view
<fx:include fx:id="logFileView" source="./sub/LogView.fxml"
maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity"
minWidth="-Infinity" prefHeight="600" prefWidth="1000"
style="-fx-background-color: rgba(0, 0, 0, 0.0);"
StackPane.alignment="CENTER_RIGHT" />
The LogView.fxml incorporates it's controller
fx:controller="auv.e4.application.analyser.controller.sub.LogViewController"
but this LogView.fxml is now placed in a common lib (bundle jar) and should be accessible by any of our GUIS's
We have like 50 different views which are structured this way and I would prefer using the FXML this way.
Another problem is the common lib will be bundle project (otherwise the RCP GUI can*t resolve them as dependencies) which makes using absolute paths impossible (Which is alo not a good practice). The GUIs are RCP based GUI's which use JavaFX for rendering.
My question is now how do I reference the LogView.fxml from an another project from inside an FXML (with fx:include) ? Is this possible ? If not what kind of restructuring should /can be be done ?

Related

Locating CSS for loading from FXML

JDK 11, JavaFX 15.
Despite the wonderful answer How do I determine the correct path for FXML files, CSS files, Images, and other resources needed by my JavaFX Application? this is still stymieing me. It does not address loading related resources.
I have a simple example loading an FXML file that refers to a CSS file.
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0"
styleClass="mainFxmlClass" xmlns:fx="http://javafx.com/fxml/1"
xmlns="http://javafx.com/javafx/11.0.1">
<stylesheets>
<URL value="#/styles/root.css" />
</stylesheets>
</AnchorPane>
And this is the pkg/App.java class:
package pkg;
public class App extends Application {
private static Scene scene;
#Override
public void start(Stage stage) throws IOException {
FXMLLoader loader = new FXMLLoader(App.class.getResource("root.fxml"));
scene = new Scene(loader.load());
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
This is the root.css file:
.mainFxmlClass {
}
Here is the jar layout (eliminating maven boiler plate, module info, manifest).
pkg/App.class
pkg/root.fxml
pkg/styles/root.css
styles/root.css
The relevant exception I get is:
Caused by: javafx.fxml.LoadException: Invalid resource: /styles/root.css not found on the classpath
According to Introduction to FXML, under Location Resolution, it says:
As strings, XML attributes cannot natively represent typed location
information such as a URL. However, it is often necessary to specify
such locations in markup; for example, the source of an image
resource. The location resolution operator (represented by an "#"
prefix to the attribute value) is used to specify that an attribute
value should be treated as a location relative to the current file
rather than a simple string.
The exception specifies "/styles/root.css", which is an absolute path. As seen from the JAR layout, I have a /styles/root.css. But the documentation says "relative to the current file".
Assuming the "current file" is /pkg/root.fxml, then /pkg/styles/root.css is (should be) relative to /pkg/root.fxml (or is it /pkg/App.class?), yet it can not locate this one either.
If I comment out the stylesheets element, the file loads just fine.
So, where should I place the root.css file?
To reference a CSS file in a FXML file you can either use:
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0"
styleClass="mainFxmlClass" xmlns:fx="http://javafx.com/fxml/1"
xmlns="http://javafx.com/javafx/11.0.1">
<stylesheets>
<String fx:value="/styles/root.css" />
</stylesheets>
</AnchorPane>
Note:
String not URL
fx:value not value
without '#' at the beginning
Seems only to support absolute paths
or
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0"
styleClass="mainFxmlClass" xmlns:fx="http://javafx.com/fxml/1"
xmlns="http://javafx.com/javafx/11.0.1"
stylesheets="#/styles/root.css" />
</AnchorPane>
Note:
attribute not nested element
comma separated list of stylesheets
stylesheet URLs must start with '#' here
supports absolute and relative URLs
The next thing is to configure the correct location, which already should be set by the constructor you're using and thus should be fine.
You can find a full sample here.
The sample uses the convention over configuration approach supported by the FXMLLoaders utility class of Drombler Commons.
With your sample this could look something like the following if you rename root.fxml to App.fxml:
scene = new Scene(FXMLLoaders.load(App.class));
It will also look for a App.properties file (and locale specific derivations ; must be in the same package) which could be useful if you have i18n text in your FXML file.
Additionally it will set the correct ClassLoader and location and throws RuntimeExceptions rather than checked exceptions since the user cannot change anything anyway.
You can use this utility class by adding the following dependency:
<dependency>
<groupId>org.drombler.commons</groupId>
<artifactId>drombler-commons-fx-core</artifactId>
<version>1.0</version>
</dependency>
The library is Open Source.

Java FX multiple scenes crash [duplicate]

New to javaFx and wanting to use scenebuilder for GUI development, i've come across an issue with no luck searching the website nor the web in general for my problem, although similar questions have been asked, thought a different perspective could be needed. I am trying to load an FXML file through Netbeans after a quick build to test functionality so the code is simple, but i cannot get the root file to be set in the controller. my code is the following
public class Divergex extends Application {
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("DivergexGUI.fxml"));
Scene scene = new Scene(root);
scene.setRoot(root);
stage.setScene(scene);
stage.show();
}
Ive tried suggestions in changing fxroot to a Vbox with no luck, i continue to get a Load exception on the compile :
Exception in Application start method...
Caused by: javafx.fxml.LoadException: Root hasn't been set. Use method setRoot() before load.
yet when i use
scene.setRoot(root);
the same exception is experienced
i've narrowed the issue down to the fact that my FXML file is unable to be set as a root in the Parent object but have had no luck in tackling this. Any suggestions would be great thanks.
<fx:root> specifies a "dynamic root" for your FXML file; this means the root of the FXML file is an object that is set on the loader prior to loading the file. This is typically used for custom controls, where you want the control to be a subclass of Node that can be instantiated using regular Java code, but want to define its layout using FXML. Proper use of <fx:root> (or at least an example of how it can be used) is shown in the standard documentation. In particular, if you use <fx:root> you must:
Create an FXMLLoader instance, instead of using the static convenience FXMLLoader.load(URL) method
Call setRoot(...) on that instance, and pass in the object that is to be the root of the FXML.
For standard FXML use, you just use a regular instance declaration as the root. Almost every example available works this way: probably the best place to start is the official tutorial. In your case, since you want a VBox, you probably just need
<VBox xmlns="javafx.com/javafx/8"; xmlns:fx="javafx.com/fxml/1"; fx:controller="divergex.DivergexGUIController">
<!-- ... -->
</VBox>
Edit If Netbeans is giving you issues, I recommend using Eclipse with the e(fx)clipse plugin. There's a very barebones, but pretty much all you need, tutorial.
uncheck id::root in scence builder
or change id::root to vbox
Just you should not use fx:root construct in scene builder.
so remove this line of code from the fxml file.
For example: <fx:root prefHeight="246.0" prefWidth="479.0" type="AnchorPane" xmlns="http://javafx.com/javafx/8.0.141" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.mycontroller">
When you create FXML file with the help of Scene Builder. It uses fx: root as a pane. Replace it with Anchor Pane
AnchorPane xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.controller.Controller
It works for me. Anyone can try, it may help for you

get FXML file nodes using java code

How to get elements or nodes from FXML file using Java, I know the way by using initialization or by setting controller class in FxmL . But I need to do it without any controller. I want to access the nodes inside the fxml file using.
My FXML COde:
HBox fx:id="hbx" id="hbx" alignment="CENTER_RIGHT" prefHeight="100.0"
prefWidth="200.0" BorderPane.alignment="CENTER"
My java Code
System.out.println(par.lookupAll("hbx"));
See my Code above, could you give me a hint?
After loading the FXML file, you can use Node#lookup():
Node node = fxmlParentPane.lookup("#nodeId");

Can I automatically generate controller classes from FXML?

As I understand it, when using FXML to describe a Java FX scene, the controller class is written manually and it's member variables and methods can then be referenced from the .fxml file. When loading the scene using the FXMLLoader, member variables are set to the corresponding scene elements and methods are wired up to the corresponding events automatically. This works but is very cumbersome as changes need to be done in two places and any mistakes will only show up at runtime.
I've seen other GUI frameworks that allow you to instead generate the controller from a scene description as an abstract class which needs to be implemented to access the scene elements and handle the events. An example of what I mean:
I would create the following .fxml file (e.g. using the JavaFX Scene Builder):
<AnchorPane ... >
<children>
<Button fx:id="button" ... text="Button" onAction="#buttonPressed" />
</children>
</AnchorPane>
Somewhere in my build process, the following .java file would be created (e.g. using a Maven plugin):
abstract class TestController {
protected final Parent root;
protected final Button button;
{
// Load test.fxml file
// Assign scene elements to root and button
// Attach event handler to the button that calls buttonClicked()
}
protected abstract void buttonClicked(ActionEvent event);
}
I could then, possibly multiple times, create a concrete implementation of that controller:
final class TestControllerImpl extends TestController {
TestControllerImpl(String buttonLabel) {
button.setText(buttonLabel);
}
#Override
protected void buttonClicked(ActionEvent event) {
button.setText("I've been clicked! What a great day!");
}
}
Is there a project with the goal to do this? Or is there a problem with this approach applied to FXML?
I see the following benefits from this approach:
Declarations for member variables and methods for the controller are automatically generated.
All member variables are final and protected instead of non-final and either public or annotated.
The same for methods, they are protected instead of either public or annotated.
Not implementing a method or misspelling it's name will lead to a compiler error.
Programmatic setup of the scene can be done in the constructor instead of an initialize() method because the constructor will run after the scene has been loaded and its elements assigned to the member variables.
This is now supported in SceneBuilder, NetBeans and in Eclipse. Note this works out of the box in NetBeans and SceneBuilder, but in Eclipse you first need the e(fx)clipse plugin.
SceneBuilder:
With an FXML file open in the editor, enter the menu to select "View" and "Show Sample Controller Skeleton".
Eclipse:
Open the fxml file so the contents are displayed in the code editing pane (you should see the fxml as plaintext xml with syntax highlighting inside Eclipse, not rendered visually in SceneBuilder). Right-click on the code in Eclipse and select "Code" and then "Generate Controller".
NetBeans:
In NetBeans it is even easier, right-click the fxml file in the project explorer and select "Make Controller".
Update Nov 2020
This answer is now outdated.
As various more recent answers have pointed out, there are now a variety of additional different tools available for automatically generating FXML controller classes from FXML documents. Many of these are targeted as extensions, features or plugins to existing development tools, such as SceneBuilder, Idea, Eclipse or NetBeans.
I suggest that interested readers review both this answer and other answers to this question, then look at their individual use-case and toolset chain and choose the solution which is most appropriate for them from the available choices.
There is nothing I know that does exactly what you propose in your question.
Likely this answer will probably end up pretty outdated over time.
Alternate Technologies
JRuby achieves most of your outlined benefits using a slightly different approach - it uses jRuby's dynamic programming magic to automatically create Ruby class members from the FXML dynamically a runtime.
Tom Schindl wrote a tool which generates Java code from FXML. Of the approaches listed in this answer, Tom's tool seems closest to your question.
SceneBuilder Skeletons
A similar Java code generator from FXML is available in SceneBuilder View | Show Sample Controller Skeleton feature, which is described in this blog post. When I use SceneBuilder, I use this feature all the time and try to keep my controllers really light so they are almost all auto generated code from the SceneBuilder skeleton feature.
It is slightly annoying though because it doesn't achieve a clean separation of generated code from hand written code, so you need to be careful when you do updates to the FXML and want to generate a new skeleton and copy and paste it over parts of your existing Controller (plus that is a slightly error prone manual operation that takes a little bit of developer time).
Source code for SceneBuilder is available if you want to see how it works.
Potential Build Tool Plugins
Such a code generation feature might make a worthwhile addition to some of the existing build tools in the JavaFX ecosystem, such as the JavaFX Maven plugin or JavaFX Gradle plugin (or a separate plugin in it's own right).
Future Development
I believe that Oracle are also working on a feature extension for FXML for a future JavaFX release (post Java 8) which compiles FXML directly to Java byte code (class files), bypassing the Java source code step. This kind of feature would probably achieve most of your outlined benefits.
It is possible with NetBeans version 8.
Open FXML , go to Source and click generate controller.
Edit: Now can be done in any IDE , Eclipse needs a plugin thought.
For Intellij Idea IDE users, FXMLManager to the rescue. See the plugin homepage
"When clicking right mouse button on .fxml file, there is new menu item "Update Controller from FXML".
Clicking this item will modify FXML Java Controller:
Remove all #FXML fields that are missing in FXML and their getters/setters
Add all #FXML fields that are missing in Controller
#Deprecate all ActionEvent methods that are missing in FXML
Create all ActionEvent methods that are missing from Controller"
As I know, there are two kind of solutions exist in netbeans.
First, netbeans's internal feature "Make Controller", which you can see with right mouse click on the fxml document. it will generate controller class which will work with FXMLLoader. The controller's java file name should be indicated in the fxml document. (left panel -> Controller -> Controller class)
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Second, netbeans's plugin "FXML 2 JAVA Converter", which you can install from menu (Tool -> Plugin -> Available Plugin -> FXML 2 JAVA Converter). and you can see "Generate Abstract Class" menu item with right mouse click on the fxml document. It will generate source code from fxml document and you can use it as an abstract class without using FXMLLoader like normal JavaFX project not JavaFXML project.
Now you can easily do it with eclipse Just do these simple steps :
Go to your fxml file that you want to create Controller for
Right Click and Click source
Click Generate Controller
Click here to see the Picture of How to do it.
If you're using IntelliJ ide, you may have to try FXML Helper plugin.
First, install the plugin from the File | Settings... | Plugins. After the installation restart the ide, Now right click on the .fxml document and select the FXML Helper menu. That`s all.
#Feuermurmel
no there is not any ways to generate automatically controller class for particula .fxml file.
you should define dynamically declare variable and method with anotation #fxml and set(bind) in scence builder.

What are the pros and cons FXML?

What are the pros and cons of using FXMLs or not using FXMLs for developing JavaFX applications?
For developing enterprise JavaFX application which approach should one follow?
FXML Cons: It takes slightly longer to load and display.
FXML Pros:
Rapid scene development / mock up using Scene Builder.
FXML is not a compiled language; you do not need to recompile the code to see the changes. Just reload the FXML file.
It provides a clear separation of GUI from logic/controller.
So you can have different versions of a scene/view using the same controller. This is handy for demo's for instance.
The content of an FXML file can be localized as the file is read.
Definitely use FXML in enterprise apps !
I would add two contra to Jurgens list.
If you are working with FXML instantiation of your view is sort of inconvenient. At least from my point of view.
Node explorer = new MyExplorerWidget();
or
Node explorer = cdicontainer.newInstance(MyExplorerWidget.class);
is more pleasant than
FXMLLoader loader = new FXMLLoader(getClass().getResource("com.mycompany.some.very.long.name.MyExplorerWidget.fxml"),explorerwidgetresouces);//Of course we want our app internationalized
Node explorer = loader.load();
Another point is that FXML is static. If you want to generate your UI at run time depending on some model you will write UI code anyway. I ended up with useless fxml files like this PropertyGrid.fxml
<AnchorPane xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8" fx:controller="PropertyGridController">
<children>
<VBox fx:id="vbox" layoutX="63.0" layoutY="-28.0" prefHeight="172.0" prefWidth="163.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
</children>
</AnchorPane>
And the PropertyGridController.
public class PropertyGridController{
#FXML
VBox vbox;
....
public void setModel(PropertySheet model){
//.... tons of code to generate the actual property grid and add it to the view
}
}

Resources