【发布时间】:2012-07-05 19:52:59
【问题描述】:
我正在尝试制作一个包含 3 个课程的应用程序。控制器(主类)、SerialHandler 和 MainWindow,它是使用 NetBeans Gui Builder 创建的 JFrame 窗体。
public class Controller {
SerialHandler serialHandler;
MainWindow mainWindow;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Controller controller = new Controller();
controller.initializeSystem(controller);
}
public void initializeSystem(Controller _controller){
mainWindow = new MainWindow(_controller);
mainWindow.setVisible(true);
}
public void anotherMethod(){
mainWindow.setMyLabelText("Hello");
}
}
所以问题是,如果我这样做并且来自 SerialHandler 类的事件调用 anotherMethod(),setMyLabelText 方法不起作用,但如果我从 initializeSystem() 调用它;它有效。
现在,如果我在 main 中声明 mainwindow,那么 mainWindow 实例在 anotherMethod() 中是不可见的。
如果我在 main 之外声明 mainWindow 对象并尝试从 main 上下文中使用它的方法,我不能,因为 mainWindow 对象已在非静态上下文之外声明。
谁能帮助我或至少为我指明正确的方向?
谢谢!
【问题讨论】:
-
您需要将引用传递给需要使用它们的对象。这可以通过构造函数参数或
setXXX(...)“setter”方法来完成。 -
你的代码不会编译 public anotherMethod() { is invalid java syntax
-
问题是如何将 mainWindow 对象传递给我创建的类?我的方法在 Controller 类中,但我在这个类中创建了我的 mainWindow ......那我该怎么办?
标签: java user-interface netbeans non-static