Using a setter from outside a form?

会有一股神秘感。 提交于 2019-12-24 11:35:58

问题


I am trying to access a form which is not static from another class which is also not static. I'd like to use a member in the class....

Public Class MainForm
public void setConsoleText(String Text){
    jTextArea1.append(Text);
}

I need to know a way to reference this setter from my class "Log" which is basically where data goes to be parsed and logged. I want it to be like this:

    private  void consoleOut(String data) {
        System.out.println(data);
        MainForm.setConsoleText("data");
    }

I cannot access this method.. I can only access MyForm.Class. Is there a way to reference the one that's been instantiated, or all of them in this virtual machine? It really doesn't matter as there will only be one of these running in this instance of the Java VM.

I just can't seem to figure this one out.


回答1:


You need to give Log a non-static MainForm variable and pass reference to the currently visualized MainForm object into the Log class and into this variable. This can be done via a Log constructor parameter or via a setter method. Then you can call methods on this instance (but checking that it's not null first). Something like:

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

Edit 1

For instance if you create your MainForm object and display it from a main method somewhere, create Log along with it and pass the visualized MainForm into the Log constructor, something like so:

public static void main(String[] args) {
   MainForm myMainForm = new MainForm();
   // ... whatever code is necessary to set up the 
   // ... MainForm object so it can be visualized
   myMainForm.setVisible(true); // and show it

   Log myLogObject = new Log(myMainForm);
   //...
}

Note that if this doesn't help you, you'll need to post more of your code.



来源:https://stackoverflow.com/questions/6400462/using-a-setter-from-outside-a-form

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