How to Capture Dialog (Swing) Focus Lost Event in Scala?

41 views
Skip to first unread message

TH Lim

unread,
Jul 11, 2011, 5:44:32 AM7/11/11
to scala-user
While I can listenTo(button) FocusLost event, I don't seem to be able
to capture FocusLost event in a Dialog (Scala's Swing Component). How
do I do that? I tried adding Publisher trait to Dialog but nothing
works. Any advice is great here.

Thanks

/lim/

john sullivan

unread,
Jul 11, 2011, 8:40:37 AM7/11/11
to TH Lim, scala-user
Hi TH,

The FocusLost events are generated by scala.swing.Component, which doesn't seem to be a superclass of the scala.swing.Dialog class. This is unfortunate as javax.swing.JDialog seemingly does generate java.awt.event.FocusEvents. (JDialog inherits from java.awt.Component, which has the java.awt.event.FocusListeners.)

I was able to work around this by reacting to FocusLost events coming from the /contents/ of the scala.swing.Dialog. It only works if I set focusable = true on those contents. I am guessing that this is because my contents is a BorderPanel, and not a simple Button or something. (I'm guessing that some widgets have focusable = true by default, but that BorderPanel doesn't.)

Anyway, here's my code. I do get FocusLost events even when having clicked on the window frame, and not the contents. That is probably because clicking on the frame gives focus to the contents of the window.

import scala.swing._
import scala.swing.Swing._
import scala.swing.BorderPanel.Position
import scala.swing.event._

object focus extends SimpleSwingApplication {

  val dialogContents = new BorderPanel {
    focusable = true
    border = EmptyBorder(30,30,30,30)
    add(new Label("label"), Position.Center)
  }

  val dialog = new Dialog(null) {
    title = "dialog"
    visible = false
    contents = dialogContents
  }

  val top = new MainFrame {
    contents = new Button(new Action("dialog") {
      def apply = {
        dialog.visible = true
      }
    })

    reactions += {
      case FocusLost(_, _, _) => println("focus lost")
    }
    listenTo(dialogContents)
  }
}



--
There are more things in heaven and earth, Horatio,
Than are dreamt of in your philosophy.

Reply all
Reply to author
Forward
0 new messages