java - how to fix the “leaking this in constructor” warning [duplicate]

夙愿已清 提交于 2020-01-05 09:04:41

问题


Possible Duplicate:
Java - Leaking this in constructor

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;
    }
}

回答1:


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);
  }
}

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




回答2:


If I understand you correctly, then the JPanel instance is being created by the JDialog. In that case you can pass the reference to the JDIalog via teh constructor of the JPanel.

In the MyJPanel class:

  public MyJPanel(JDialog dialog) {
    initComponents();
    this.dialog = dialog;
  }

And in the JDialog at the point where you create the MyJPanel you can do this:

  myPanel = new MyJPanel(this);



回答3:


You can stick with @SuppressWarnings("LeakingThisInConstructor"), beacuse all UI objects are created in a single thread in Swing app, so there is no problem to pass this on the last line of the consturctor of Swing component.



来源:https://stackoverflow.com/questions/9380044/java-how-to-fix-the-leaking-this-in-constructor-warning

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!