简体   繁体   English

如何处理JPanel-jPanel1.dispose()或等效方法

[英]How to Dispose a JPanel - jPanel1.dispose() Or equivalent

How can we dispose() a JPanel? 我们如何处置()JPanel?

I've done jPanel1.removeAll() and now I want JPanel to be disposed so that jPanelParent.getComponents() can't return it 我已经完成了jPanel1.removeAll() ,现在我希望处理JPanel,以便jPanelParent.getComponents()无法返回它

Component[] components = this.jPanelParent.getComponents();  /// Returns 5 Components      
JPanel last = (JPanel)components[components.length];
last.removeAll();
//last.dispose()   NOT AVAILABLE

Now after above code if I run .getComponents() I don't want to get "last" in above code 现在在上面的代码之后,如果我运行.getComponents(),我不想在上面的代码中获得“最后一个”

This is a classic case of looking in the wrong place for an answer; 这是在错误的地方寻找答案的经典案例。 your question presupposes a way to do things, and you ask how to do that presupposed and erroneous operation, and confusion ensues. 您的问题以一种做事的方式为前提,而您又问该怎么做,即错误的操作和随之而来的混乱。 It doesn't help that "dispose" is a term used for an operation you don't need at all, having to do with making memory available for reclaiming in an environment where programmers do these things. “ dispose”是一个您根本不需要的操作所使用的术语,这无济于事,这与在程序员执行这些操作的环境中提供可回收的内存有关。

I believe what you want to do is remove the reference that the parent component has to the JPanel. 相信您要做的是删除父组件对JPanel的引用。 That would fit your desire that getComponents() in the parent panel not return the panel you are getting rid of. 这将符合您希望父面板中的getComponents()不返回您要摆脱的面板的要求。

In order for the panel that you are removing to do this, it needs a reference to the parent panel, and then you can remove it from the parent panel just like you've removed components from the target panel. 为了使要删除的面板能够执行此操作,它需要引用父面板,然后可以将其从父面板中删除,就像从目标面板中删除了组件一样。 In fact, if the parent panel is the only place that references the target, and the target's components are only referenced in the target, you don't have to remove the target components if you just remove the parent panel reference to the target. 实际上,如果父面板是唯一引用目标的位置,并且仅在目标中引用了目标的组件,则只需删除对目标的父面板引用,就不必删除目标组件。

So pass a reference to your parent panel to your target panel, and do a remove() of the target panel from the parent panel in place of your hypothesized dispose() call. 因此,将对父面板的引用传递到目标面板,然后从假设的dispose()调用中将目标面板从父面板中移除()。

Dispose em JPanel Netbeans java 处置em JPanel Netbeans Java

   Component comp = SwingUtilities.getRoot(this);
   ((Window) comp).dispose();

In my case, my one panel was on a JDialog, and the following can work: 在我的情况下,我的一个面板在JDialog上,并且可以正常工作:

public void dispose() {
    JFrame parent = (JFrame) this.getTopLevelAncestor();
    parent.dispose();
}

However, I think explicitly keeping a reference to the parent in the panel might be a less error prone way, as described in another answer. 但是,我认为在面板中显式地保留对父级的引用可能不太容易出错,如另一个答案中所述。

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

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