如何在 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)
最佳答案
我知道这个问题已经两年了,但我认为值得更新另一个答案。这是我的解决方案:
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)
一些注意事项:
contents +=
构造所以我的弹出菜单代码看起来像其他 scala-swing 菜单构造代码。 JPopupMenu.setVisible
,我想你会想要包装和使用方法 JPopupMenu.show
,因此您可以控制弹出菜单的位置。 (只要将它设置为可见,我就会将它放在屏幕的左上角。)关于swing - Scala 弹出菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/938753/