1
votes

I just started working with Swing. I'm starting to get the hold of it.

However I got a question regarding screen navigation in swing.

This is how I have structured the app.

  • public class MainFrame extends JFrame
  • public class LoginPanel extends JPanel
  • public class HomeScreenPanel extends JPanel

in Mainframe I have the following code:

public class MainFrame extends JFrame {

    public MainFrame() {
        initUI();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                MainFrame ex = new MainFrame();
                ex.setVisible(true);
            }
        });
    }

    private void initUI(){
        InputScreenPanel inputScreenPanel = new InputScreenPanel();
        getContentPane().add(inputScreenPanel);
        Dimension dim = new Dimension(400, 300);
        setMinimumSize(dim);
    }
}

In LoginPanel I initialize the screen and add a button and a textbox. I wrote the event handler for the button click event. I want to get the value from the textbox and redirect the user to HomeScreenPanel. How can I switch the panel when at the time this button click is executing the context is the LoginPanel and there I have no reference to the frame so I can switch the panels.

3
I think, first you'll have to design the program before starting to code. For this, you can try to implement MVC pattern.manas
You could opt for a CardLayout as well and just switch between the panelsRobin

3 Answers

3
votes

I think you have 2 options here:

  1. You could pass the MainFrame object as a parameter when creating your InputScreenPanel. You should ask yourself if it makes sense that your InputScreenPanel knows about your MainFrame. In some situations it might, but based on your example I would say no and go for the second option.
  2. You can create some kind of event handler structure for your InputScreenPanel (or any model structure behind it if you are using a Model-View-Controller design). The user would login, this would create an event, which the MainFrame (or another class) could respond to.
2
votes

You should use a JDialog for the login part and then start your app in a new JFrame

1
votes

I'd use some kind of model/controller that is capable of reacting to changes within the separate parts of the program.

I'd interface this controller so you can replace the implementation without effecting the rest of the application

Basically this would mean that the login pane and the home panes wouldn't care about how they are being displayed