How do I recognize mouse clicks in Scala?

2019-07-03 23:43发布

问题:

I'm writing a small GUI program. Everything works except that I want to recognize mouse double-clicks. However, I can't recognize mouse clicks (as such) at all, though I can click buttons and select code from a list.

The following code is adapted from Ingo Maier's "The scala.swing package":

import scala.swing._
import scala.swing.event._

object MouseTest extends SimpleGUIApplication {
  def top = new MainFrame {
    listenTo(this.mouse) // value mouse is not a member of scala.swing.MainFrame
    reactions += {
      case e: MouseClicked =>
        println("Mouse clicked at " + e.point)
    }
  }
}

I've tried multiple variations: mouse vs. Mouse, SimpleSwingApplication, importing MouseEvent from java.awt.event, etc. The error message is clear enough--no value mouse in MainFrame--so, where is it then? Help!

回答1:

Maybe that way?

object App extends SimpleSwingApplication {
  lazy val ui = new Panel {
    listenTo(mouse.clicks)
    reactions += {
      case e: MouseClicked =>
        println("Mouse clicked at " + e.point)
    }
  }
  def top = new MainFrame {
    contents = ui
  }
}

BTW, SimpleGUIApplication is deprecated



回答2:

The MouseClicked event has an attribute clicks, which should be 2 if it was a double-click. Have a look at java.awt.event.MouseEvent for the original source if you're curious.