Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Responding to key events in scala

I'm experimenting with a bit of Scala gui programming (my first project in scala, so I thought I'd start with something simple). But I seem to have got stuck at something that seems like it should be relatively trivial. I have a class that extends scala.swing.MainFrame, and I'd like to detect when a user presses a key when that window has focus. Funny thing is I don't seem to be able to find any way to get that event to fire.

I found an example of how someone else had got around the problem here: http://houseofmirrors.googlecode.com/svn/trunk/src/src/main/scala/HouseGui.scala but they seem to have reverted to using the Java Swing API, which is a little disappointing. Does anyone know if there's a more idiomatic way of intercepting events?

like image 484
Ceilingfish Avatar asked Jun 28 '10 21:06

Ceilingfish


2 Answers

This seems to work with Scala 2.9

package fi.harjum.swing

import scala.swing._
import scala.swing.event._
import java.awt.event._

object KeyEventTest extends SimpleSwingApplication {
    def top = new MainFrame {
        val label = new Label {
            text = "No click yet"
        }
        contents = new BoxPanel(Orientation.Vertical) {
            contents += label
            border = Swing.EmptyBorder(30,30,10,10)
            listenTo(keys)
            reactions += {
                case KeyPressed(_, Key.Space, _, _) =>
                    label.text = "Space is down"
                case KeyReleased(_, Key.Space, _, _) =>
                    label.text = "Space is up"
            }
            focusable = true
            requestFocus
        }
    }
}      
like image 169
Mika Harju Avatar answered Sep 20 '22 23:09

Mika Harju


In addition to listening to this.keys you should also call requestFocus on the component or set focusable=true, if it is Panel or derived class.

like image 30
Oleg Avatar answered Sep 17 '22 23:09

Oleg