Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
604 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 Reply

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.)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...