简体   繁体   English

如何从JFrame添加/删除JPanel

[英]How to add/remove a JPanel from a JFrame

I'm trying to set a variable to be a new JPanel and then add it once a button is pressed, but it is not working and I don't know why. 我试图将变量设置为新的JPanel ,然后在按下按钮后将其添加,但是它不起作用,我也不知道为什么。

code: 码:

private void nextButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
    remove(scriptPanel);
    scriptPanel = new GemPanel();
    add(scriptPanel);
    validate();
    repaint();
    pack();
}    

GemPanel is just a JPanel class I made. GemPanel只是我创建的JPanel类。 When I press the next button, it re-sizes the frame to be as small as possible and nothing actually happens. 当我按下下一个按钮时,它将帧的大小调整为尽可能小,并且实际上什么也没有发生。 If I re-size it to normal, the original scriptPanel is still there. 如果我将其调整为正常大小,则原始scriptPanel仍然存在。

What gives? 是什么赋予了?

Instead of trying to remove and add entire panels, a better, less problem prone approach would be to use a CardLayout that will allow to swap views. 与其尝试删除和添加整个面板,不如使用一种更好的,较少出现问题的方法,将使用CardLayout来交换视图。 You can see more at How to use Cardlayout 您可以在如何使用Cardlayout中查看更多信息

Also, by the looks of your method signature, it seems you're using the Netbeans builder too. 而且,从方法签名的外观来看,似乎您也在使用Netbeans构建器。 You may also want to take a look at How to Use CardLayout with Netbeans Gui Builder 您可能还想看看如何在Netbeans Gui Builder中使用CardLayout

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

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