masnun
masnun

Reputation: 11906

Import Issue while trying to load JavaFX class in Jython

I have sample Jython code for JavaFX like this:

# hello.py
from javafx.application import Application
from javafx.scene import Scene
import javafx.scene.control
from javafx.scene.layout import AnchorPane

class Hello(Application):
    def start(self, stage):
        stage.setTitle("Hello, World!")

        root = AnchorPane()
        label = javafx.scene.control.Label("Hello, World!")
        root.getChildren().add(label)

        scene = Scene(root, 100, 40)
        stage.setScene(scene)

        stage.show()


if __name__ == '__main__':
    Application.launch(Hello().class, [])

Here, I can do import javafx.scene.control and later use it like javafx.scene.control.Label("Hello, World!") but why can't I do from javafx.scene.control import Label?

Here's Jython info:

$ jython
Jython 2.5.3 (2.5:c56500f08d34+, Aug 13 2012, 14:48:36)
[Java HotSpot(TM) 64-Bit Server VM (Oracle Corporation)] on java1.8.0_25
Type "help", "copyright", "credits" or "license" for more information.
>>>

Upvotes: 2

Views: 887

Answers (1)

davidrmcharles
davidrmcharles

Reputation: 1953

If you move your from/import statement inside of your start method, immediately before you need the Label control, I bet your code will work.

With Jython running on JavaFX8, there are certain things that you cannot do (such as import controls) until the JavaFX runtime has been started. (JavaFX2 was not this picky.) For this reason, starting the JavaFX runtime is the very first thing your Jython/JavaFX program should do. (I have a module specifically for doing this.) Then you can import everything else.

As an aside, I do not think you want to use the from/import approach, but rather the import/as approach. The former defeats caching, while the latter does not.

Upvotes: 2

Related Questions