java - how to fix the “leaking this in constructor

2019-07-23 12:58发布

问题:

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.