1

我正在尝试制作一个有 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 对象并尝试从 main 上下文中使用它的方法,我不能因为 mainWindow 对象已在非静态上下文之外声明。

任何人都可以帮助我或至少指出我正确的方向吗?

谢谢!

4

1 回答 1

2

您的代码存在设计不一致:

   public static void main(String[] args) {
        // TODO code application logic here
       Controller controller = new Controller();
       controller.initializeSystem(controller);
   }
   public void initializeSystem(){
       mainWindow = new MainWindow(_controller);
       mainWindow.setVisible(true);
   }

您正在创建作为参数传递给它的控制器,initializeSystem这是多余的,因为您可以在this内部使用initializeSystem

你应该这样做:

   public static void main(String[] args) {
        // TODO code application logic here
       Controller controller = new Controller();
       controller.initializeSystem();
   }
   public void initializeSystem(Controller _controller){
       mainWindow = new MainWindow(this);
       mainWindow.setVisible(true);
   }

第二个不一致是anotherMethod访问您的 UI 并更新其中内容的方法。你应该把它留给控制器。像这样的东西:

public class Controller {
     //...

     public void updateUIText(String text){
           SwingUtilities.invokeLater(new Runnable() {
              public void run() {
                mainWindow.setMyLabelText("Hello");
              }
           });
     }
}

现在,SerialHandler可以在需要时通过 Controller 更新 UI。您所要做的就是传递ControllerSerialHandler

编辑请注意,我使用SwingUtilities.invokeLater来更新 UI,这将确保Controller即使在我认为是您的情况的多线程场景中也能正确更新 UI

于 2012-07-05T20:15:41.517 回答