【问题标题】:Passing integers with constructors使用构造函数传递整数
【发布时间】:2012-04-14 15:38:34
【问题描述】:

好的,那么

  • 创建了新的 Zombie 变量。
    private Zombie zombieA;
  • 僵尸变量已初始化

    zombieA = new Zombie(1);
  • 在 Zombie 类中调用构造函数:

    public Zombie(int type) {
    this.type = type;
    x=200;
    y=100;
    dx=1;
    paintA.setColor(Color.RED);}
    

基本上,我希望游戏类创建一个新的 Zombie,类型为 1,它将通过 switch 和 case 来确定要创建的僵尸类型(级别 1=10)。问题是当我运行它时,我的应用程序强制关闭并且出现错误:

zombieA = new Zombie(1);

从初始类和错误:

public Zombie(int type) {

来自僵尸类。我一遍又一遍地检查它,我只是看不到问题,有人注意到有什么问题吗?

【问题讨论】:

  • 堆栈跟踪?我只是在阅读 LogCat,它说 java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
  • @AlexBath - 请完整的堆栈跟踪:行号、调用的类和方法。看不出问题,因为构造函数参数没有问题..

标签: java android class constructor


【解决方案1】:

没有堆栈跟踪很难说,但我怀疑问题出在这一行:

paintA.setColor(Color.RED);

您确定paintA 已正确初始化吗?在我看来,它是 null 并在您的构造函数中导致 NullPointerException 。如果是这种情况,请务必先实例化它,如下所示:

paintA = new ...

【讨论】:

  • 呃,总是小事-_-。谢谢,效果很好。我将其设置为 Paint paintA,paintB = new Paint(); 只需将其更改为在构造函数中进行初始化,感谢您的帮助!
【解决方案2】:

您是在工作线程中调用 Zombie 类吗?您需要从 UI 线程执行此操作,这里有一些示例:Can't create handler inside thread that has not called Looper.prepare()

【讨论】:

  • 我相信我是从 UI 线程中调用它的。我对线程的掌握充其量是薄弱的,但我有一个游戏类,里面有一个类 GamePanel 扩展了surfaceview并实现了runnable,我从run方法中调用了Zombie类,谢谢,我会尝试改变它回复你。
  • 如果你得到“Can't create handler inside thread that has not called Looper.prepare()”,你肯定不会在 UI 线程上调用它。
猜你喜欢
  • 1970-01-01
  • 2017-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多