java-如何解决“在构造函数中泄漏"的问题;警告 [英] java - how to fix the "leaking this in constructor" warning

查看:108
本文介绍了java-如何解决“在构造函数中泄漏"的问题;警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
Java-在构造函数中泄漏

Possible Duplicate:
Java - Leaking this in constructor

在NetBeans中,我有一个包含JPanel的JDialog.我试图将JDialog的引用传递给JPanel.请在下面查看我的代码.当我这样做时,会收到在构造函数中泄漏此"警告.我知道原因,但不知道如何解决.我也知道我可以使用@SuppressWarnings("LeakingThisInConstructor"),但是在不抑制警告的情况下,没有真正的方法来解决此问题吗?

In the NetBeans I have a JDialog that contains a JPanel. I am trying to pass a reference of the JDialog to the JPanel. Please take a look at my code below. When I do it the way I did I receive the "Leaking this in constructor" warning. I understand why, but I don't know how to fix this. I also know that I can use @SuppressWarnings("LeakingThisInConstructor") but isn't there a real way to fix this without suppressing the warning?

public class MyJDialog extends javax.swing.JDialog {

    public MyJDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        MyJPanel.getThis(this);
    }
}

public class MyJPanel extends javax.swing.JPanel {

    private JDialog dialog;

    public MyJPanel() {
        initComponents();
    }

    public void getThis(JDialog dialog){
        this.dialog = dialog;
    }
}

推荐答案

构造函数将返回对该对话框的引用.创建实例后,让面板自行设置变量.

The constructor will return a reference to the dialog. Have the panel set the variable itself once the instance is created.

public class MyJPanel extends JPanel {
  private JDialog dialog;

  public MyJPanel(Frame aFram) {
    dialog = new MyJDialog(aFrame, true);
  }
}

此外,该代码将不起作用,因为getThis()不是静态方法,因此需要引用MyJPanel实例.

Also, that code will not work because getThis() is not a static method, thus requires a reference to a MyJPanel instance.

这篇关于java-如何解决“在构造函数中泄漏"的问题;警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆