在Scala类构造函数中访问val字段时出现NullPointerException

时间:2016-05-14 15:31:01

标签: swing scala

我想将类似以下Java代码的内容翻译成Scala:

private HashMap<KeyStroke,Action>actionMap=new HashMap<KeyStroke,Action>();

KeyStroke left = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0);
//....
actionMap.put(left, new AbstractAction("move left") {
    @Override
    public void actionPerformed(ActionEvent e) {
        doSomething();
    }
}

我最初的尝试是:

import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import java.awt.event.KeyEvent
import java.awt._
import javax.swing.JFrame
import javax.swing.JPanel
import javax.swing.Action
import javax.swing.AbstractAction
import javax.swing.KeyStroke
import collection.mutable.HashMap
object Main{
  def main(args:Array[String]){
    val gui:GUI = new GUI()
  }
}

class GUI extends JFrame{
  initKeyboard
  pack
  this.setVisible(true)
  private val actionMap = new HashMap[KeyStroke,Action]
  def initKeyboard{
    val left = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT,0)
    actionMap.put(left, new AbstractAction("Move Left"){
      override def actionPerformed(e:ActionEvent){
        println("Do something")
      }
    })//actionMap.put
  }

}

请注意,我还没有编写代码来对actionMap做任何事情。

但是我在运行时遇到以下错误:

Java.lang.NullPointerException
    at GUI.initKeyboard(Game.scala:24)
    at GUI.<init>(Game.scala:18)
    at Main$.main(Game.scala:13)
    at Main.main(Game.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

(注意第24行是启动“actionMap.put”的行)

应如何实施?

1 个答案:

答案 0 :(得分:2)

问题在于初始化顺序。

在新的GUI实例创建中,列出的顺序执行以下操作:

initKeyboard
pack
this.setVisible(true)
private val actionMap = new HashMap[KeyStroke,Action]

您可以在初始化initKeyboard之前看到您致电actionMap 。因此,在initKeyboard内访问它会引发异常。

您可以使用以下简单示例验证初始化顺序:

class GUI extends {
  initKeyboard
  private val actionMap = println("actionMap")
  def initKeyboard: Unit = {
    println("initKeyboard")
  }
}
new GUI // prints: initKeyboard actionMap