Response to key events in scala

I am experimenting with a little gui Scala programming (my first project in scala, so I thought I would start with something simple). But I seem to be stuck in the fact that it seems to be relatively trivial. I have a class that extends scala.swing.MainFrame, and I would like to determine when the user presses a key, when this window has focus. It's funny that I can't seem to find a way to fire this event.

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

+6
scala swing keyevent
source share
5 answers

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 would seem to work, even if there were no button objects attached to this component, or any of them.

0
source share

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 } } } 
+6
source share

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

+3
source share

I expect you to listen to this.keys (where this is the GUI element that receives keyboard events). See Equivalent mouse event question.

+1
source share

Instead of returning to java events, all components have keys that publishes these events (so there is no MainFrame ). Not sure what the best solution is, but you can always wrap everything in a frame inside a Component and listen to its keys .

0
source share

All Articles