有一个类有静态方法:ChangePanel
,它会将静态JPanel的内容更改为新内容。 Frame是静态JPanel的变量名。
public static void ChangePanel(JPanel jp)
{
Javaassignment1b.Driver.Frame.getContentPane().removeAll();
Javaassignment1b.Driver.Frame.add(jp);
Javaassignment1b.Driver.Frame.validate();
}
此静态方法在JPanel上实现时按预期工作,该功能由actionlistener添加。
示例
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;
}
当我尝试通过JOptionPane的返回值更改静态JPanel的内容时,我不明白为什么它不起作用
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;
}
使用调试器显示我的代码已执行但是它并没有改变静态Jpanel内容,我怀疑它可能与线程有关,有人可以帮我解决这个问题
注意:我知道CardLayout是更换JPanel的更好选择,但由于遗留原因,我需要弄清楚
由于