javafxgroovyfx

In GroovyFX, how to modularize the page layout?


I'm fairly new to JavaFX and GroovyFX.

I just build my first form on JavaFX, and as soon I got it working I ported it to GroovyFX because I'm on a Groovy/Grails development team.

I'd like to know how to modularize the page layout, that is, how to extract the nodes definitions under the GroovyFX.start() method.

Let's say I have the following simple layout:

start{
    stage(title: 'GroovyFX Hello World', visible: true){
        scene(width: 300, height: 100){
            borderPane{
                center(align: CENTER){
                    text "this is the center region"
                }
            }
        }
    }
}

I can extract code into closures under the start method:

start{

    def renderCenter = {
        text "this is the center region defined in a closure"
    }

    stage(title: 'GroovyFX Hello World', visible: true){
        scene(width: 300, height: 100){
            borderPane{
                center(align: CENTER){
                    renderCenter()
                }
            }
        }
    }
} 

But what I want is:

class CenterRegion {
    def render(){
        text "this is the center region in a separate class"
        // and other stuff
    }
}

start{
    stage(title: 'GroovyFX Hello World', visible: true){
        scene(width: 300, height: 100){
            borderPane{
                center(align: CENTER){
                    CenterRegion.render()
                }
            }
        }
    }
}

How can I accomplish this with GroovyFX?

Thanks


Solution

  • import groovyx.javafx.SceneGraphBuilder
    import static groovyx.javafx.GroovyFX.start
    
    class CenterRegion {
        static def render(SceneGraphBuilder builder){
            builder.text "some centered text"
        }
    }
    
    start {
        // get the ScenGraphBuilder by getting closure's delegate
        def sgb = getDelegate()
    
        stage(title: 'GroovyFX Hello World', visible: true){
            scene(width: 300, height: 100){
                vbox {
                    borderPane{
                        center(align: CENTER){
                            CenterRegion.render(sgb)
                        }
                    }
                }
            }
        }
    }