是否有一个更简单的表单可以替换新的ActionListener()?

时间:2018-02-22 17:49:00

标签: scala intellij-idea

为了创建一些带有单行的按钮,如:

val buttonPanel = new JPanel()
buttonPanel.add(makeButton("Action #1", myEventListener.doActionOne))
buttonPanel.add(makeButton("Action #2", myEventListener.doActionTwo))
buttonPanel.add(makeButton("Action #3", myEventListener.doActionThree))

我创建了这个方法makeButton

def makeButton(title: String, callback: () => Unit) = {
  val button = new JButton(title)
  button.addActionListener(new ActionListener(){def actionPerformed(e: ActionEvent): Unit = callback()})
  button
}

Intellij标记new ActionListener()并发出警告,并提议更改它。允许更改导致:

def makeButton(title: String, callback: () => Unit) = {
  val button = new JButton(title)
  button.addActionListener((e: ActionEvent) => callback())
  button
}

这导致未使用的变量e,但更重要的是,它会在运行时导致此错误:

Error:(90, 47) type mismatch;
 found   : java.awt.event.ActionEvent => Unit
 required: java.awt.event.ActionListener
    button.addActionListener((e: ActionEvent) => callback())

这里是否有可以手动应用的简化,或者Intellij可以应用?

1 个答案:

答案 0 :(得分:0)

这会有用吗?

def makeButton(title: String, callback: () => Unit) = {
  val button = new JButton(title)
  val listener: ActionListener = (e: ActionEvent) => callback()
  button.addActionListener(listener)
  button
}