Skip to content
Advertisement

JavaFX invoking Java methods using JavaScript

My application is completely styled in a web document form (HTML, CSS & JavaScript), and I’m only using JavaFX WebView to load it as a normal resource.

I would like to invoke a method from one of my classes (a Java code) using JavaScript.

Like for example, a simple Hello World to the console:

JavaScript

How can I invoke the world() method in this case?

So my code from the page is something like this:

JavaScript

Any way to achieve this?


UPDATE

Notice: For those people who were looking for a complete and simple example about how to achieve this, you can test all the following codes written below.

I’ve finally achieved my goal, thanks to sir @Oshan_Mendis’ answer. This example is based from this tutorial from Oracle docs: 6 Making Upcalls from JavaScript to JavaFX.

But here, I’ll be using my own code, the main goal is to call a method from Java code using JavaScript from the HTML page.

File contents:

JavaScript

1. Creating the Main-Class (Main.java)

JavaScript

2. Preparing the Main layout (main.fxml)

JavaScript

3. Setting up the web page (Controller.java)

JavaScript

4. Preferred class and its method to invoke (Hello.java)

JavaScript

5. Main layout web page content (index.html)

JavaScript

Note: You can perform other mouse-related events other than onclick event in this case like: onmouseenter, onmouseover, onmousemove, onmouseup, etc.. But I’m not really sure if these are the only supported events of invoking methods.

Advertisement

Answer

This is well explained in the Java API Documentation under Calling back to Java from JavaScript

JavaScript

You can then refer to the object and the method from your HTML page:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement