views:

84

answers:

2

Hi chaps, 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?

+1  A: 

I expect you need to listen to this.keys (where this is the element of the GUI receiving the keyboard events). See the equivalent question about mouse event.

Daniel
Thx Daniel, I needed this too. The scala's swing documentation is really poor.
Aymen
`this.keys` doesn't seem to be a valid attribute of `scala.swing.MainFrame`. Nor does `this.Keys`, `this.Keyboard` or `this.keyboard`. Is there any documentation on this anywhere?
Ceilingfish
@Ceilingfish Not the `MainFrame`, but a `Component`: labels, panels, text areas, etc. And, of course, `this` refers to the component itself.
Daniel
A: 

My solution for this required me to do the following:

class MyFrame extends MainFrame {

this.peer.addKeyListener(new KeyListener() {
    def keyPressed(e:KeyEvent) {
      println("key pressed")
    }

    def keyReleased(e:KeyEvent) {
      println("key released")
    }

def keyTyped(e:KeyEvent) {
      println("key typed")
    }
 })

}

This only seemed to work though if there were no button objects attached to this component, or any of it's children.

Ceilingfish