我有一个 class 的引用,它是空的

I have a reference to a class that is null

我正在尝试在另一个 class 中执行一个方法,但我的引用是空的。

我有一个主计算器 class,它的开头是这样的:

public class Calculator {

public static void main( String[] args ) {

    // create new model, view and controller
    Model theModel = new Model();
    View theView = new View();
    Controller theController = new Controller( theModel, theView );

    /* start it up */
    theView.CalcView();

视图 class 中,我创建了一些按钮,将控制器注册为监听器:

    btnZero = new JButton( "0" );
    btnZero.addActionListener( new Controller() );
    btnZero.setBounds( 167, 174, 86, 23 );
    frame.getContentPane().add( btnZero );

也在 视图中 class 我捕获按下的键:

    private void keyPressed( KeyEvent e, Controller controller ) {
    controller.keyPressed( e );
}

我当前的objective是在视图class中从控制器class[=执行一个方法38=] 击键 view.toggleBorder( '1', true );:

    public void keyPressed( KeyEvent e ) {
    char key = e.getKeyChar();

    switch ( key ) {
    case '1':
    System.out.println( "1" );
    view.toggleBorder( '1', true );
    break;

控制器构造函数:

    public Controller( Model model, View view ) {
    this.model = model;
    this.view = view;

}

但我也有一个无参数构造函数,我在将控制器注册为侦听器时必须创建它,如您在上面的按钮代码中所见。问题是,当涉及 view.toggleBorder.. 时,对 view 的引用为空,因此它会抛出空指针异常。我认为我的 classes 和声有问题,但我找不到哪里可能有问题。这段代码是支离破碎的,我深表歉意。您可以在 GitHub

上查看源文件

您的视图需要引用控制它的控制器。您注册到按钮的实例不知道视图或模型。

在视图中创建一个名为 setController 的方法,您必须在构造控制器后调用该方法

// create new model, view and controller
Model theModel = new Model();
View theView = new View();
Controller theController = new Controller( theModel, theView );

 theView.setController(theController);

如果您愿意,您可以在控制器构造函数中这样做

在您的视图中 class 当您初始化所有按钮和组件时,您 运行 btnOne.addActionListener( new Controller() ); 每个按钮。这样做的问题是您正在为每个按钮创建一个新的控制器实例,none 其中有您的模型或视图对象的实例。

您在这里遇到的另一个问题是您有两个 class,并且每个都需要另一个 class 的完整功能实例才能完全发挥作用。

解决此问题的一种方法是在计算器中创建 Controller 的静态实例变量 class,然后向 Controller 添加方法以将其提供给 View 和 Model。仅使用静态实例将监听器添加到按钮,并且仅在 Controller 具有 View 实例后才添加监听器。