There is a class which has a static method : ChangePanel
which will change the content of a static JPanel to new content. Frame is the variable name of the static JPanel .
public static void ChangePanel(JPanel jp)
{
Javaassignment1b.Driver.Frame.getContentPane().removeAll();
Javaassignment1b.Driver.Frame.add(jp);
Javaassignment1b.Driver.Frame.validate();
}
This static method works as expected when it is implemented on a JPanel whose functionality is added by actionlistener.
Example
public class AdminLoginPanel extends JPanel
{
AdminLoginPanel()
{
pwlabel = new JLabel("Password");
pwfield = new JPasswordField(20);
loginbutton = new JButton("Login");
loginbutton.addActionListener(new LoginButtonListener());
add(pwlabel);
add(pwfield);
add(loginbutton);
}
private class LoginButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
char[] password = pwfield.getPassword();
//convert from char array to String
String password2 = new String(password);
admin = new Admin();
if (admin.checkPassword(password2))
{
//show Admin panel
//works in this case
AdminMenuPanel amp = new AdminMenuPanel();
Utility.ChangePanel(amp);
}
else
{
//text box appear to state password is incorrect
ErrorMessagePanel emp = new ErrorMessagePanel("Wrong password, please try again");
}
}
}
JLabel pwlabel;
JPasswordField pwfield;
JButton loginbutton;
Admin admin;
}
I dont understand why is it not working when I try to change the content of the static JPanel through the return value of JOptionPane
public class RetryPanel extends JPanel
{
RetryPanel()
{
jp = new JOptionPane();
//reply will be 1 for No , 0 for yes
int reply = JOptionPane.showConfirmDialog(null,"Would you like to start a new game ???","Message Title",JOptionPane.YES_NO_OPTION );
if ( reply == 0)
{
//player wants to play a new game , retry
}
else
{
//player wants to quit
//doesnt work in this case
SelectAdminUserPanel saup = new SelectAdminUserPanel();
Utility.ChangePanel(saup);
}
}
JOptionPane jp;
}
Using a debugger shows that my code is executed however it just doesnt change the static Jpanel content , I suspect it may have something to do with threads , can someone help me resolve this issue
note : I know CardLayout would be a better alternative for changing JPanel but for legacy reasons , I need to figure this out
Thanks