Reputation: 70
I am writing a program where there is a JFrame with a JPanel with a login gui. After logging in successfully, a method is called that clears the JFrame. The issue I am having is that instead of clearing the JFrame, the stuff in the JPanel is still visibly there and it is just frozen.
Method that creates login gui:
public void logingui() {
JPanel loginpanel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 2;
JLabel gamename = new JLabel("InvestGame By Ama291");
gamename.setFont(new Font("Arial", 1, 22));
loginpanel.add(gamename, c);
c.ipady = 20;
c.gridx = 0;
c.gridy = 1;
loginpanel.add(new JPanel(), c);
c.ipady = 10;
c.gridwidth = 1;
c.gridx = 0;
c.gridy = 2;
loginpanel.add(new JLabel("Username: "), c);
c.gridx = 1;
final JTextField userfield = new JTextField(10);
loginpanel.add(userfield, c);
c.gridx = 0;
c.gridy = 3;
loginpanel.add(new JPanel(), c);
c.gridx = 0;
c.gridy = 4;
loginpanel.add(new JLabel("Password: "), c);
c.gridx = 1;
final JPasswordField passfield = new JPasswordField(10);
loginpanel.add(passfield, c);
c.gridx = 0;
c.gridy = 5;
c.ipady = 20;
loginpanel.add(new JPanel(), c);
c.ipady = 10;
c.gridx = 0;
c.gridy = 6;
c.gridwidth = 1;
JButton createacc = new JButton("Create Account");
loginpanel.add(createacc, c);
c.gridx = 1;
JButton login = new JButton("Log In");
loginpanel.add(login, c);
add(loginpanel);
}
Method to clear JFrame:
public void gamegui() {
JPanel gamepanel = new JPanel();
removeAll();
invalidate();
validate();
repaint();
add(gamepanel);
}
Does anyone know how I can successfully remove the JPanel from the JFrame without the buttons and stuff from the JPanel frozen inside of the window? This is the issue I'm having.
Upvotes: 1
Views: 435
Reputation: 11
When removing components from a JFrame, the component will be removed but it will visually still be there. Therefore, to hide it or refresh the JFrame, use the .setVisible(false) method.
Upvotes: 1
Reputation: 653
if you ll just add
this.setLayout(your layout)
//your layout=the layout which you are using. i.e border,card etc..
between the invalidate() and validate() methods in your code in gamegui().
I hope it ll work . I havent tried but hope it ll work.
Upvotes: 0
Reputation: 324108
For a login it is probably better to use a popup JDialog. Then when the dialog closes you just display the panel on the frame.
The other option is to use a Card Layout. The you can swap panels as required.
Upvotes: 2