斯卡拉阿卡NullPointerException异常错误(Scala Akka NullPoint

2019-11-05 02:43发布

我有一个Boot类和Drawer演员。 所以,当我按下按钮,我把起动器的参数。 在Drawer演员我越来越Starter ,并说自己的呼叫Fill 。 我想,以填补矩形,但是当我打电话Fill ,我得到一个错误:空java.lang.NullPointerException 。 如何解决这个问题呢?

引导类:

import akka.actor.{Actor, ActorSystem, Props}
import javafx.application.Platform
import scalafx.Includes._
import scalafx.application
import scalafx.application.JFXApp
import scalafx.scene.Scene
import scalafx.scene.canvas.Canvas
import scalafx.scene.control.Alert.AlertType
import scalafx.scene.control.{Alert, ButtonType}

object Boot extends JFXApp {

  private val system = ActorSystem("MYsystem")
  private val drawer = system.actorOf(Props(new Drawer(g)), "Drawer")

  val wiDth = 500
  val heiDth = 500
  val canvas = new Canvas(wiDth, heiDth)
  val g = canvas.graphicsContext2D

  private val alert = new Alert(AlertType.Information) {
    title = "Hello Player"
    headerText = "Do you want to start game?"
    contentText = null
    buttonTypes = Seq(ButtonType.Cancel, ButtonType.OK)
  }

  private val result = alert.showAndWait()

  result match {
    case Some(ButtonType.OK) => drawer ! Drawer.Starter(50,50)
    case Some(ButtonType.Cancel) => Platform.exit()
  }

  canvas.setFocusTraversable(true)

  new application.JFXApp.PrimaryStage {
    title = "Tanks"
    scene = new Scene(wiDth, heiDth) {
      content = canvas
    }
  }
}

抽屉演员

import akka.actor.{Actor, ActorLogging, ActorRef}
import javafx.scene.canvas.GraphicsContext

object Drawer{
  case object DrawBullet
  case class Starter(x:Int,y:Int)
  case class Fill( x:Int, y:Int)
}

class Drawer(g:GraphicsContext) extends Actor with ActorLogging {
  import Drawer._

  override def receive: Receive = {

    case Starter(newx,newy)=>
      self ! Fill(newx,newy)

    case Fill(newx,newy) =>
      g.fillRect(newx,newy,50,50)
  }
}

Answer 1:

你的问题被称为“向前引用” -你正在使用g你初始化之前。

下面的代码重新产生此。

import akka.actor.{Actor, ActorLogging, ActorRef}
import akka.actor.{Actor, ActorSystem, Props}
import stackoverflow.Drawer.{Fill, Starter}

object AcalaAkkaNPE_51853920 extends App {
  def aFunctionThatCreatesG() = new G()


  private val system = ActorSystem("MYsystem")
  private val drawer = system.actorOf(Props(new Drawer(g)), "Drawer")

  drawer ! Fill(5,2)

  val g = aFunctionThatCreatesG()

}

object Drawer{
  case object DrawBullet
  case class Starter(x:Int,y:Int)
  case class Fill( x:Int, y:Int)
}

class Drawer(g:G) extends Actor with ActorLogging {
  override def receive: Receive = {

    case Starter(newx,newy)=>
      self ! Fill(newx,newy)

    case Fill(newx,newy) =>
      println(g)
  }
}

class G {
  override def toString: String = "I'm G"
}


文章来源: Scala Akka NullPointerException error
标签: scala akka