簡體   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