[英]How to replace current JPanel with another JPanel?
當我按Admin按鈕時,我試圖從同一JPanel
的UserAdminPanel
過渡到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);
}
}
我認為您應該對主框架有一個參考,只需根據按下的按鈕從其中刪除組件,然后僅添加所需的組件即可。 用您所說的話, 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.