代码之家  ›  专栏  ›  技术社区  ›  oxbow_lakes

scala弹出菜单

  •  3
  • oxbow_lakes  · 技术社区  · 16 年前

    如何使弹出窗口在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)
    
    2 回复  |  直到 16 年前
        1
  •  4
  •   dcstraw    16 年前

    你做的很好,但是如果你想隐藏对等呼叫,你可以创建自己的类:

    class PopupMenu extends Component
    {
      override lazy val peer : JPopupMenu = new JPopupMenu
    
      def add(item:MenuItem) : Unit = { peer.add(item.peer) }
      def setVisible(visible:Boolean) : Unit = { peer.setVisible(visible) }
      /* Create any other peer methods here */
    }
    

    然后你可以这样使用它:

    val item = new MenuItem(new Action("Say Hello") {
      def apply = println("Hello World");
    })
    
    val popup = new PopupMenu
    popup.add(item)
    popup.setVisible(true)
    

    作为替代方案,您可以尝试Squib(scala古怪的用户界面构建器)。使用爆炸管时,上述代码变为:

    popup(
      contents(
        menuitem(
          'text -> "Say Hello",
          actionPerformed(
            println("Hello World!")
          )
        )
      )
    ).setVisible(true)
    
        2
  •  6
  •   sullivan-    14 年前

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

    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 */
    }
    

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

    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)
    

    需要注意的一些事项:

    1. 按照中的建议使用supermixin类 scala-swing-design.pdf 在“打包机编写指南”一节的“使用打包机缓存”小节中。
    2. 混合scala.swing.sequentialContainer.wrapper以便使用 contents += 构造,使弹出菜单代码看起来像其他scala swing菜单构造代码。
    3. 当问题使用 JPopupMenu.setVisible ,我想你要用这个方法包装 JPopupMenu.show ,这样您就可以控制弹出菜单的位置。(只需将其设置为可见,我就可以将其放在屏幕的左上角。)
    推荐文章