Search code examples
tornadofx

Swapping a fragment in a view in TornadoFX


It looks complicated, but basically I have a borderpane with three components, the center of which is a fragment (the red box). I should be able to change any of the three menus at the top, and the fragment should be replaced with another generated fragment. Instead of replacing the fragment, it removes everything on the screen except the original fragment. The simplified code is below the images.

A GUI, a portion of which is surrounded by a red box

The GUI with only the fragment in the red box left

The parent view uses a borderpane, the fragment is a vbox.

The parent:

override val root = borderpane {

    top = menus.root

    center = searchBoxes.root

    bottom = bottomHalf.root
}

The swap function:

fun swapSearchBoxes() {

    val parentView = find(GfeSearchViewParent::class)
    val newSearchBoxes = stateContext.createNewSearchBoxes()

    parentView.root.center.replaceWith(newSearchBoxes.root)
}

Is there a way to make this work without regenerating the whole parent view?


Solution

  • The problem seems to have been a question of scope. When I originally called the parent view, I simply instantiated an instance which did not define the scope. Once I added the parent view by find, it quit wiping out everything else in the parent panel and began updating properly.

    Example:

    class ParentTabFrame : View() {
    
    // wrong
    val parentView = ParentView()
    
    //right
    val parentView = find(ParentView::class)
    
    override val root ...
    
    }
    

    I believe using inject would also solve the problem. (Source: the TornadoFX documentation on Scopes.)