0

So I have this swing GUI and I'm trying to figure out how to switch panels/screens when the button is clicked but right now the first panel goes away but the second one won't show up.

public class GUI {
    static JFrame mainFrame = new JFrame();
    public GUI () {
        openLoginScreen();
    }
    private static void openLoginScreen() {
        JPanel loginPanel = new JPanel();
        JButton newAccountButton = new JButton ("Create New Account");
        newAccount.addActionListener (new ActionListener () {
            public void actionPerformed (ActionEvent e) {
                mainFrame.remove(titlePanel);
                mainFrame.repaint();
                openNewAccountScreen();
            }
        } );
        loginPanel.add(newAccountButton);
        mainFrame.add(loginPanel);
    }
    private static void openNewAccountScreen() {
        JPanel newAccount = new JPanel();
        mainFrame.add(newAccount);
    }
}

I've tried just removing one panel and adding another or repainting after doing both or repainting in between and nothing seems to be working :( Obviously I left out a bunch of other stuff that are in the program but this is basically what the problem is. Any help would be very appreciated or tips in general. I'm still fairly new to swing. Thx :D

faris
  • 692
  • 4
  • 18
  • Short answer is, like all answers to this type of question, Swing layouts are lazy, that is, it is your responsibility to notify them when you want the container to be relayed out. In order to do this, you will need to call `revalidate` and `repaint` to trigger a new layout and paint pass. A better answer to this type of question is, use a `CardLayout` - it's designed to do this job – MadProgrammer Mar 03 '18 at 21:57

1 Answers1

2

I think you need to add revalidate or repaint

bajen micke
  • 309
  • 1
  • 7
  • 18
  • oh yay that worked i didn't know revalidate was necessary thx – faris Mar 03 '18 at 21:54
  • Use a [`CardLayout`](http://download.oracle.com/javase/8/docs/api/java/awt/CardLayout.html) as shown in [this answer](http://stackoverflow.com/a/5786005/418556). – Andrew Thompson Mar 04 '18 at 03:45