Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
618 views
in Technique[技术] by (71.8m points)

swing - Scala Popup Menu

How do I cause a popup to get shown in Scala? I have a "backdoor" but it seems pretty ugly to me:

val item = new MenuItem(new Action("Say Hello") {
  def apply = println("Hello World");
})
//SO FAR SO GOOD, NOW FOR THE UGLY BIT!
val popup = new javax.swing.JPopupMenu
popup.add(item.peer)
popup.setVisible(true)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I know the question is two years old, but I think it's worth updating with another answer. Here's my solution:

import javax.swing.JPopupMenu
import scala.swing.{ Component, MenuItem }
import scala.swing.SequentialContainer.Wrapper

object PopupMenu {
  private[PopupMenu] trait JPopupMenuMixin { def popupMenuWrapper: PopupMenu }
}

class PopupMenu extends Component with Wrapper {

  override lazy val peer: JPopupMenu = new JPopupMenu with PopupMenu.JPopupMenuMixin with SuperMixin {
    def popupMenuWrapper = PopupMenu.this
  }

  def show(invoker: Component, x: Int, y: Int): Unit = peer.show(invoker.peer, x, y)

  /* Create any other peer methods here */
}

Here is some sample usage code:

val popupMenu = new PopupMenu {
  contents += new Menu("menu 1") {
    contents += new RadioMenuItem("radio 1.1")
    contents += new RadioMenuItem("radio 1.2")
  }
  contents += new Menu("menu 2") {
    contents += new RadioMenuItem("radio 2.1")
    contents += new RadioMenuItem("radio 2.2")
  }
}
val button = new Button("Show Popup Menu")
reactions += {
  case e: ButtonClicked => popupMenu.show(button, 0, button.bounds.height)
}
listenTo(button)

Some things to note:

  1. Use of SuperMixin class as recommended in scala-swing-design.pdf, in section "Guidelines for Writing Wrappers", subsection "Use the wrapper cache".
  2. Mixin scala.swing.SequentialContainer.Wrapper so that I can use the contents += construct so my Popup Menu code looks like other scala-swing Menu construction code.
  3. While the question uses JPopupMenu.setVisible, I think you are going to want to wrap and use the method JPopupMenu.show, so you can control the location of the Popup Menu. (Just setting it to be visible puts it in the top left-hand corner of the screen for me.)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...