我有一个 Frame(此处命名为“MainApplication”),它主要有一个 JPanel 来显示信息,具体取决于上下文。
启动时,MainApplication 有一个空的 JPanel。
然后它创建一个“LoginRequest”类,该类创建一个简单的登录/密码表单,并将其发送回 MainApplication,后者将其显示在其 JPanel 中。
“LoginRequest”类实现了 ActionListener,所以当用户点击“Login”按钮时,它会检查登录名/密码是否正确,如果用户被授予,我想卸载该表单,并显示MainApplication Frame 上的主屏幕。
所以,要做到这一点,我想出了这个:
public class LoginRequest implements ActionListener {
protected MainApplication owner_m = null;
public LoginRequest(MainApplication owner_p) {
owner_m = owner_p;
}
@Override
public void actionPerformed(ActionEvent event_p) {
// the user just clicked the "Login" button
if (event_p.getActionCommand().equals("RequestLogin")) {
// check if login/password are correct
if (getParameters().isUserGranted(login_l, password_l)) {
// send an ActionEvent to the "MainApplication", so as it will
// be notified to display the next screen
this.owner_m.actionPerformed(
new java.awt.event.ActionEvent(this, 0, "ShowSummary")
);
} else {
messageLabel_m.setForeground(Color.RED);
messageLabel_m.setText("Incorrect user or password");
}
}
}
}
然后,“MainApplication”类(扩展 JFrame):
public class MainApplication extends JFrame implements ActionListener {
protected void load() {
// create the panel to display information
mainPanel_m = new JPanel();
// on startup, populate the panel with a login/password form
mainPanel_m.add(new LoginRequest(this).getLoginForm());
this.add(mainPanel_m);
}
@Override
public void actionPerformed(ActionEvent event_p) {
// show summary on request
if (event_p.getActionCommand().equals("ShowSummary")) {
// remove the previous information on the panel
// (which displayed the login form on this example)
mainPanel_m.removeAll();
// and populate the panel with other informations, from another class
mainPanel_m.add(...);
...
...
}
// and then refresh GUI
this.validate();
this.repaint();
this.pack();
}
}
当 ActionEvent 从“LoginRequest”类发送到“MainApplication”类时,它会执行代码,但最后什么也没发生,就好像 JFrame 没有重新绘制一样。
有任何想法吗 ?
谢谢,