我正在创建一个具有以下面板的GUI:
保存程序中所有面板的主框架:
public class Main extends JFrame {
private Signup signupForm;
private Login login;
private UserScreen user;
private JPanel cards;
private CardLayout cl;
private static final int INNER_FRAME_WIDTH=800;
private static final int INNER_FRAME_HEIGHT=800;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, INNER_FRAME_HEIGHT, INNER_FRAME_WIDTH);
getContentPane().setLayout(new GridLayout(0, 1, 0, 0));
cards = new JPanel();
getContentPane().add(cards);
cl = new CardLayout();
cards.setLayout(cl);
login = new Login();
cards.add(login,"login");
signupForm = new Signup();
cards.add(signupForm,"signup");
ActionListener listen = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try{
//check for a user with the parameters from userName and password fields . On success create a UserScreen for the current user.
//This means that you need to send the User object to the UserScreen c'tor. It should look something like this. Might need to change UserScreen accordingly.
user = new UserScreen();
cards.add(user,"user");
cl.show(cards,"user");
}
catch (Exception exception){ //TODO: Change to exception thrown from Client constructor
//TODO: Have the exception popup the relevant screen.
}
}
};
login.loginBtn.addActionListener(listen); << Example of setting a button's actionListener from Main.
setLoginListeners();
setSignupListeners();
}
}
“登录”面板 - 这是您打开程序时遇到的屏幕。
注册面板 - 按下登录面板中的“注册”按钮即可进入此屏幕。
用户屏幕 - 显示用户信息的屏幕。
我遇到了一个我不确定如何处理的问题:
单击“登录”面板中的“登录”按钮后,我想切换到新用户的屏幕(UserScreen对象)。 由于类Login无法访问UserScreen对象(只有Main框架有),我不得不从Main类设置按钮的actionListener,这似乎是一个糟糕的解决方案(因为它要求我给许多主要访问权限) “登录”面板中的字段,以便检查具有给定用户名和密码的用户是否存在等)。有没有更好的办法?
有没有比我得到的更好的解决方案?
答案 0 :(得分:1)
您应该实现模型 - 视图 - 控制器模式,不同视图之间的交互应始终通过控制器。
http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller