2009-06-02 51 views
3

如何让弹出窗口在斯卡拉显示?我有一个“后门”,但它看起来很丑对我说:斯卡拉弹出式菜单

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) 

回答

4

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

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的新奇的用户界面生成器)。随着SQUIB,上面的代码变成:

popup(
    contents(
    menuitem(
     'text -> "Say Hello", 
     actionPerformed(
     println("Hello World!") 
    ) 
    ) 
) 
).setVisible(true) 
+0

为什么这个(弹出菜单)不是标准scala swing工具包的一部分?我必须说,由于缺乏文档以及一些非常基本的构造,我感到有点惊慌。让我怀疑是否有人实际使用该工具包。 – 2009-06-03 07:12:45

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

下面是一些示例使用代码:

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. Mixin scala.swing.SequentialContainer.Wrapper,这样我就可以使用contents +=构造,所以我的弹出菜单代码看起来像其他的scala-swing菜单构造代码。
  3. 虽然问题使用JPopupMenu.setVisible,我想你会打算使用方法JPopupMenu.show,所以你可以控制弹出菜单的位置。 (只要将它设置为可见就会将它放在屏幕的左上角)