java 擦除 Swing 内容窗格/面板并显示新面板

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4939949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 08:42:09  来源:igfitidea点击:

Erase Swing Content Pane/Panel & display a new panel

javaswing

提问by Jim

I have created an applet where when you press the button "Forgot Pass" I erase the current JPanel on the applet & create a new JPanel that displays the JComponents related to Retrieving/Forgetting a password.

我创建了一个小程序,当您按下“忘记密码”按钮时,我会擦除小程序上的当前 JPanel,并创建一个新的 JPanel,显示与检索/忘记密码相关的 JComponent。

I can successfully clear the JPanel using .removeAll(); BUTafter I create all my new JComponents & add them to the content pane (main JPanel) the applet just goes gray & doesn't show the new JPanel & components UNLESSI resize the applet, then it repaints & works.

我可以使用 .removeAll(); 成功清除 JPanel;但是在我创建所有新的 JComponents 并将它们添加到内容窗格(主 JPanel)之后,小程序只是变灰并且不显示新的 JPanel 和组件,除非我调整小程序的大小,然后它会重新绘制和工作。

I have tried putting .invalidate() after I have created all the new JComponents but that still doesn't refresh the applet?

我已经尝试在创建所有新 JComponents 后放置 .invalidate() ,但仍然没有刷新小程序?

How can I make my JPanel appear after I clear it with .removeAll() & add different JComponents to it?

在使用 .removeAll() 清除 JPanel 并向其添加不同的 JComponents 后,如何使 JPanel 出现?

Code:

代码:

public class App extends JApplet
{
    JPanel mainPanel; 

    public void init()
    {
        SwingUtilities.invokeAndWait( new Runnable() {
            public void run()
            {
                showLoginPanel(); // this shows fine on loading
            }
        });

    }

    public void showForgotPassPanel()
    {
        mainPanel.removeAll();

        mainPanel = (JPanel) getContentPane();
        Box hBox  = Box.createHorizontalBox();
        Box vBox  = Box.createVerticalBox();
        mainPanel.setLayout( new BorderLayout() ); 

        ... create components

        ... add components to mainPanel

        mainPanel.invalidate(); // doesn't make new layout visible, not unless I resize the applet
    }
}

回答by POSIX_ME_HARDER

Use mainPanel.revalidate();and/or mainPanel.repaint();methods.

使用mainPanel.revalidate();和/或mainPanel.repaint();方法。

回答by Hovercraft Full Of Eels

Another "clean" option is to swap views with a CardLayout. It does all the dirty work for you behind the scenes.

另一个“干净”的选择是用 CardLayout 交换视图。它在幕后为您完成所有肮脏的工作。