2015-07-20 94 views
0

我是一名玩scala swing的scala新手。並想翻譯scala.swing.Pointscala.swing.event.MousEventScala;類型(X)=> X的表達式不符合類型SupX

我想將鼠標事件發送給負責處理形狀選擇的類。但是因爲一個形狀相對於他的容器有一個位置(),但是MouseEvent.point是相對於之前我應該​​翻譯/相關的窗口。

所以,我有一個Selection類誰收到MouseEvent S:

case class Selection(sheet:Sheet) { 

    def on(event:Event) = event match { 
    case clicked:MouseClicked => { 
     clicked.modifiers match { 
     case scala.swing.event.Key.Modifier.Control => 
      sheet.getItemAt(clicked.point).map(addToSelection) 
     case _ => 
      sheet.getItemAt(clicked.point).map(setSelection) 
     } 
    } 
    } 
} 

而一個Sheet誰是他的形狀容器(並知道如何翻譯點)。

class Sheet extends Component { 
    private val selection = Selection(this) 

    listenTo(mouse.clicks, mouse.moves) 
    reactions += { 
    case e:MousePressed => selection.on(translate(e)) 
    case e:MouseClicked => selection.on(translate(e)) 
    } 

    /** Here is my problem : 
    * > Expression of type (MouseEvent) => MousePressed doesn't conform to expected type Event 
    */ 
    def translate(original: MouseEvent): Event = original match { 
    case pressed:MousePressed => 
     pressed.copy(point=relativize(pressed.point)) 
    case clicked:MouseClicked => 
     clicked.copy(point=relativize(pressed.point)) 
    case other:MouseEvent=> 
     other 
    } 
} 

我可以用一個醜陋的投繞過這個問題:

case pressed:MousePressed => 
     pressed.copy(point=relativize(pressed.point)).asInstanceOf[MousePressed] 

但後來我有另一個更奇怪的編譯器的問題:

Error:(32, 21) missing arguments for method copy in class MousePressed; follow this method with `_' if you want to treat it as a partially applied function

pressed.copy(point = relativize(pressed.point)).asInstanceOf[MousePressed]

在這裏,我迷路了,並需要你幫忙做這個簡單的轉換。

當然,所有的方法都使用scala.swing._類型(和scala.swing之間從不混合。and java.awt中。`)

非常感謝

回答

1

關於編譯器的問題,你能理解的抱怨關於查看MouseEvent(特別是MousePressed)文檔。

的情況下,類有兩個參數列表定義,下列簡化簽名

MousePressed(source: Component, point: java.awt.Point, modifiers: Modifiers, clicks: Int, triggersPopup: Boolean)(peer: java.awt.event.MouseEvent) extends MouseButtonEvent 

正如你可以看到有第二個參數列表期待peer對象,它是底層的Java Swing對象。您可以使用相同的名稱的屬性(如pressed.peer

copy方法,通過案例類定義生成,大概預計,第二個參數訪問peer情況下,像這樣的

pressed.copy(point = relativize(pressed.point))(pressed.peer) 

隨着第二參數列表缺失,編譯器推斷要部分地應用copy方法,因此建議您使用

pressed.copy(point = relativize(pressed.point) _ 

語法爲partially applying咖喱功能

+0

非常感謝。而且它消除了投射的需要(我的Ide需要誰來解決這個錯誤的表達方式) –

相關問題