0

I have a JFrame which is initialized as follows:

setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(PREFERRED_SIZE);
setTitle("Game Set");

setLayout(new BorderLayout());
background = new JLabel(new ImageIcon("images/gameSetBackground.jpg"));
background.setPreferredSize(PREFERRED_SIZE);
add(background);

loginPane = new LoginPane();

background.setLayout(new GridBagLayout());
loginPane.setOpaque(false);
background.add(loginPane, constraints);

pack();
setVisible(true);

I did it this way because it let me set the background to the jpg I specify. Now I have the loginPane() class as follows:

public class LoginPane extends JPanel {
    JLabel label = new JLabel("Login");
    JLabel secondLabel = new JLabel("If you don't have a profile, click below to create one!");
    JTextField userName;
    JPasswordField password;

    public LoginPane() {
        setLayout(new GridBagLayout());

        userName = new JTextField(20);
        password = new JPasswordField(20);

        constraints.insets = new Insets(2, 2, 2, 2);
        constraints.gridx = 0;
        constraints.gridy = 0;
        add(label, constraints);

        // etc add all of them the same way

        constraints.gridy = 3;
        add(secondLabel, constraints);

        userName.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                password.requestFocus();
            }
        });

        password.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (userName.getText().equals("Mike")) {
                }
            }
        });
    }
}

What I want to happen is that when I hit enter after a username and password has been entered, I will check if that is a valid username/password pair. After that I want to remove everything here and display a different JPanel. Inside the password.ActionListener, I tried the following:

loginPane.removeAll();

background.removeAll();

Those were two separate cases, but both cause the JFrame to crash, the TextFields become unresponsive and I have to exit out. What am I doing wrong?

mike
  • 1,318
  • 3
  • 21
  • 41

1 Answers1

3

"JFrame crashes when trying to replace a panel with another panel"

Simple/and correct solution would be to use a CardLayout to switch between panels. See more at How to use CardLayout and see a simple example here.

The CardLayout has methods like show() to to show a certain panel by name, next() to show the next panel, and previous() to show the previous panel. This is preferred way, over removing and adding panels.

Community
  • 1
  • 1
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720