我正在创建一个具有以下面板的 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 类中设置按钮的 actionListener,这似乎是一个糟糕的解决方案(因为它要求我向 Main 授予对许多对象的访问权限)登录面板中的字段,以便它可以检查具有给定用户名和密码的用户是否存在等)。难道就没有更好的办法了吗?
还有比我现有的更好的解决方案吗?
最佳答案
您应该实现模型- View - Controller 模式,不同 View 之间的交互应始终通过 Controller 进行。
http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
关于java - JPanel 和处理它们之间的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21170588/