OO 中的重要概念之一是职责分离。
在您的情况下,Login
组件不负责决定在成功登录后应该采取什么行动(您也可以争辩不成功)。
在这种情况下,您需要让登录组件通过某种方式通知相关方登录过程的状态。这最好使用观察者模式之类的东西来实现。
基本上,这意味着您有某种可以对更改做出反应的侦听器/回调。
在下面的示例中,我使用 aCardLayout
作为切换视图的主要方法,但是您可以很容易地使用 aJDialog
作为登录表单(就像 Hovercraft 所做的那样)并在处理登录后加载主框架成功地。
public class TestCardLogin {
public static void main(String[] args) {
new TestCardLogin();
}
public TestCardLogin() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel implements LoginListener {
private MainPane mainPane;
private LoginPane loginPane;
public TestPane() {
setLayout(new CardLayout());
mainPane = new MainPane();
loginPane = new LoginPane(this);
add(mainPane, "MAIN");
add(loginPane, "LOGIN");
((CardLayout) getLayout()).show(this, "LOGIN");
}
@Override
public void loginSuccessful() {
((CardLayout) getLayout()).show(this, "MAIN");
}
@Override
public void loginFailed() {
JOptionPane.showMessageDialog(TestPane.this, "Login failed", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public class MainPane extends JPanel {
public MainPane() {
JLabel label = new JLabel("Welcome!");
Font font = label.getFont();
label.setFont(font.deriveFont(Font.BOLD, 32));
setLayout(new GridBagLayout());
add(label);
}
}
public class LoginPane extends JPanel {
private JTextField user;
private JPasswordField password;
private JButton login;
private LoginListener loginListener;
public LoginPane(LoginListener listener) {
this.loginListener = listener;
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(4, 4, 4, 4);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.EAST;
add(new JLabel("User name:"), gbc);
gbc.gridy++;
add(new JLabel("Password:"), gbc);
gbc.gridx++;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
user = new JTextField(12);
password = new JPasswordField(12);
add(user, gbc);
gbc.gridy++;
add(password, gbc);
login = new JButton("Login");
gbc.gridx = 0;
gbc.gridy++;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(login, gbc);
login.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
boolean accept = (boolean) (((int) Math.round(Math.random() * 1)) == 0 ? true : false);
if (accept) {
loginListener.loginSuccessful();
} else {
loginListener.loginFailed();
}
}
});
}
}
public interface LoginListener {
public void loginSuccessful();
public void loginFailed();
}
}