java - 从 ActionListener 返回值

标签 java return actionlistener

我有一个实现 ActionListener 的方法。在类的底部我有一些 get 方法。但是,每当我调用另一个类中的 get 方法时,我都会收到 NullPointerException。

package com.FishingGame.Screen;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class HandleActions implements ActionListener{

private boolean goFishing = false, sell = false, checkW = false;
private int test = 12;

public HandleActions(){

}



void resetAllVars(){
    goFishing = false;
    sell = false;
    checkW = false;
}

public void actionPerformed(ActionEvent e) {
    String bSource = e.getActionCommand();

    resetAllVars();

    if(bSource == "go fishing"){

        System.out.println("1");
        goFishing = true;

    }else if(bSource == "sell"){

        System.out.println("2");
        sell = true;

    }else if(bSource == "check weather"){

        System.out.println("3");
        checkW = true;

    }
}

public boolean getGoFishing(){
    return goFishing;
}
public boolean getSell(){
    return sell;
}
public boolean getCheckW(){
    return checkW;
}
public int getTest(){
    return test;
}

}

public class Game implements Runnable {

HandleActions h;
Window w;

public Game() {

    w = new Window(600, 400, "Game");
    w.add(w.mainScreen());
    w.setVisible(true);
    System.out.println(h.getTest());
}

Thread thread = new Thread(this);


@Override
public void run() {


    }

public static void main(String args[]) {
    Game g = new Game();


    }

}

控制台显示错误来自 h.getTest() 调用。这是否与 HandleActions 类实现 ActionListener 有关。我可以从其他类返回值。

最佳答案

变量未初始化

 HandleActions h;
 public Game() {
  h =new HandleActions(); //initialize
  ... 
}

关于java - 从 ActionListener 返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39313461/

相关文章:

c++ - C++ 编译器会优化掉未使用的返回值吗?

bash - 评估 bash "&&"退出代码行为

javascript - 双重嵌套函数值返回停止进入双重嵌套函数

java - 如何用一个替换一打 Action 监听器?

java - 如何捕获异步执行中的 astyanax 失败

java - Android sqliteOpenHelper onUpgrade 用新数据库替换数据库

java - 图的 HashMap 表示

java - 如何在 Android 中将嵌套的 Arraylist 存储在 Bundle 中

java - 为什么 Java 按钮使用字符串命令而不是枚举?

java - 在我的游戏中实现 ActionListener 第 2 部分