如何从实例创建者之外的另一个类访问方法



我创建了3个Java文件:main.java,gui.java,serial.java

在主我创建了两个Java文件的实例。我可以从Main内调用GUI和串行的方法。我无法从Main外部的GUI和串行中调用方法。

package main;
 public class Main {
        public static void main(String[] args) {
            GUI gui = new GUI();
            gui.setVisible(true);
            Serial serial = new Serial();
            serial.getPorts();
            fillList();
        }
        public void fillList () {
            gui.setList("hoi");
        }
    }

为什么?如何从方法填充列表中调用GUI的方法?感谢您的任何见解。

该实例仅存在于其声明的方法中,在这种情况下为构造函数。解决此问题的一种常见方法是在您的课程中声明field,并在构造函数(或其他方法(中分配该字段的值。尝试:

package main;
public class Main {
    // private GUI gui; // replaced this line with the below. See comment 5
    private static GUI gui; // this is the new field declaration
    public static void main(String[] args) {
        gui = new GUI(); // note I removed the class declaration here since it was declared above.
        gui.setVisible(true);
        Serial serial = new Serial();
        serial.getPorts();
        fillList();
    }
    public void fillList () {
        gui.setList("hoi"); // now this method has access to the gui field 
    }
}

最新更新