Search code examples
user-interfacejavafxpanels

Javafx app with many pages


I've got a question about building a gui in javafx.

When I build a program with many pages, I mean for example - The start page contains a couple of buttons "Add user", "Drop user", "Change user data" - each of these buttons draws an different panel. And here is my question - how to organise them. When I put all panels in one class it becomes quickly huge and generates many many bugs. It's also hard to find a part of code which is broken. Should every panel be defined in a different class? But if so, there is a problem with returning from submenus to main menu.

Or another example. First panel of program is login page and the next page depends on the inserted login.

How should I organize a lot of panels? Any help would be appreciated :)


Solution

  • If your project is not too big, then i would suggest making a Presenter class, which would control the stage and the program flow and which shows up one of many View classes.

    This is an example of a presenter class:

    class Presenter {
    
    public void showA(Stage mainStage){
        ViewA a = new ViewA();
        a.setOnBackButton(new ViewCallback(){
            public void call(){
                showB();
            }
        });
        mainStage.setScene(new Scene(a));
    }
    
    public void showB(Stage mainStage){
        ViewB b = new ViewB();
        b.setOnBackButton(new ViewCallback(){
            public void call(){
                showA();
            }
        });
        mainStage.setScene(new Scene(b));
    }
    
    }
    

    This is example of a view body:

    public class ViewA {
    
    private ViewCallBack onBackButton = null;
    
    public void setOnBackButton(ViewCallback callback){ onBackButton = callback; }
    
    public void callBack() { if (onBackButton != null) onBackButton.call(); }
    
    ...
    
    // somewhere in your code
    Button b = new Button("shoot me!");
    b.setOnAction(new EventHandler<ActionEvent>(){
        public void handle(ActionEvent event){
            callBack();
        }
    });
    
    }
    

    This is the ViewCallback interface

    public Interface ViewCallback {
        public void call();
    }
    

    You can use this simple callback interface or Callback<P,R> JavFX generic callback interface.