Scala弹出菜单

oxb*_*kes 3 swing scala popup

如何在Scala中显示弹出窗口?我有一个"后门"但对我来说似乎很难看:

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)
Run Code Online (Sandbox Code Playgroud)

sul*_*an- 6

我知道问题是两年了,但我认为值得用另一个答案进行更新.这是我的解决方案:

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 */
}
Run Code Online (Sandbox Code Playgroud)

以下是一些示例用法代码:

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)
Run Code Online (Sandbox Code Playgroud)

有些事情需要注意:

  1. 使用scala-swing-design.pdf中建议的SuperMixin类,"编写包装器指南","使用包装器缓存"小节.
  2. Mixin scala.swing.SequentialContainer.Wrapper以便我可以使用contents +=构造使我的Popup Menu代码看起来像其他scala-swing菜单构造代码.
  3. 问题使用时JPopupMenu.setVisible,我认为您将要包装并使用该方法JPopupMenu.show,因此您可以控制弹出菜单的位置.(只是将其设置为可见,将它放在屏幕的左上角.)