Referencing a dynamic setter from a dynamic class

2019-09-05 06:56发布

问题:

I am trying to reference a setter... I received help and selected the answer too soon before resolving the issue.... see here: Using a setter from outside a form?

So, what I'm doing is this... Data goes into the log and it gets parsed, then it goes back to the form where it is displayed.

public class Log {
   private MainForm mainForm; // our MainForm variable

   public Log(MainForm mainForm) {
      // setting the MainForm variable to the correct reference in its constructor
      this.mainForm = mainForm;  
   }

   private  void consoleOut(String data) {
     System.out.println(data);
     if (mainForm != null) {
        // now we can use the reference passed in.
        mainForm.setConsoleText("data");
     }
   }
}

Here's the setter in my form.

public class MainForm extends FrameView {
    public MainForm(SingleFrameApplication app) {
        super(app);
...........CUT FOR LENGTH.................
    public void setConsoleText(String Text){
        jTextArea2.append(Text);
    }

edited for simplicity sake.

For some reason MainForm always comes out null in the Log class.

How can I get a reference to my Main form?

Meh... I just went with a static textbox and a static setter.... Still looking for a better idea.

回答1:

The only explanation is that when you are instantiating Log you are passing a null to the constructor. Are you calling new Log(mainform) before mainform has been assigned?

// Don't do this
private Log log = new Log(mainForm);

private MainForm mainForm = new MainForm();

Check the order of construction of your objects.