繁体   English   中英

如何用另一个JPanel替换当前的JPanel?

[英]How to replace current JPanel with another JPanel?

当我按Admin按钮时,我试图从同一JPanelUserAdminPanel过渡到AdminLogin

UserAdmin面板

在此处输入图片说明

过渡到AdminLogin面板

在此处输入图片说明

现在的问题是我要打开一个新面板,而不是将当前面板更改为新面板。

这是我的UserAdminPanel代码

public class SelectAdminUserPanel extends JPanel 
{
    public SelectAdminUserPanel()
    {
        setLayout(new GridLayout(3,1));
        JButton b1 = new JButton("User Login");
        JButton b2 = new JButton("Admin Login");
        JButton b3 = new JButton("Exit");

        b1.addActionListener(new  SelectUserButtonListener() );
        b2.addActionListener(new SelectAdminButtonListener());
        b3.addActionListener(new SelectExitButtonListener() );

        add(b1);
        add(b2);
        add(b3);
    }

    private class SelectAdminButtonListener implements ActionListener
    {

        public void actionPerformed(ActionEvent event)
        {
            AdminModule am = new AdminModule();

              am.run();   
        }
    }

    private class SelectUserButtonListener implements ActionListener
    {
        public void actionPerformed(ActionEvent event)
        {
              GameModule gm = new GameModule();
              gm.run(); 
        }
    }

    private class SelectExitButtonListener implements ActionListener
    {
        public void actionPerformed (ActionEvent event)
        {

        }
    }
}

这是AdminLogin面板的代码

public class AdminLoginPanel extends JPanel
{
    AdminLoginPanel()
    {         
        JLabel pwlabel = new JLabel("Password");
        JPasswordField pwfield = new JPasswordField(20);
        JButton loginbutton = new JButton("Login");

        add(pwlabel);
        add(pwfield);
        add(loginbutton);
     }
}

我看了以下示例和该示例,但是它不是很适用,因为它谈论CardLayout而不是像重写当前JPanel

我认为您应该对主框架有一个参考,只需根据按下的按钮从其中删除组件,然后仅添加所需的组件即可。 用您所说的话, UserAdminPanel是您的主面板。 我认为它已添加到您可以获取参考的框架中。 当您单击一个按钮时,您要删除其上显示的所有内容,并仅显示该按钮应显示的内容。 我认为应该看起来像这样:

private class SelectAdminButtonListener implements ActionListener {

        public void actionPerformed(ActionEvent event) {
             frame.getContentPane().removeAll();
             AdminModule am = new AdminModule();
             frame.add(am.getNewPanel());
             frame.pack();                    
             // am.run();   //it's not clear what does for you
        }

}

方法getNewPanel()将返回基础JPanel 我假设AdminModule具有对参考AdminLoginPanel

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM