我尝试在点击时创建一个包含更多选项(例如菜单项选项)的Scala按钮/标签。
目前我有;
val expandableLabel = new Label {
icon = new ImageIcon("myimage.png")
listenTo(this)
reactions += {
case e: MouseClicked => println("Hey, stop clicking. It tickles.")
}
}
但我真正想要的是能够点击图像并查看选项列表(例如复选框选项)。这在Scala中是否可行?
编辑:我相信这可以通过CSS来完成,但我想知道的是,纯粹的Scala是否可行。
答案 0 :(得分:1)
您可以使用弹出式菜单:
import scala.swing._
val pop = new PopupMenu {
contents += new MenuItem(Action("Foo")(println("Clicked Foo")))
contents += new MenuItem(Action("Bar")(println("Clicked Bar")))
}
new Frame {
contents = new Label("Click me") {
border = Swing.EmptyBorder(4)
listenTo(mouse.clicks)
reactions += {
case _: event.MouseClicked =>
pop.show(this, 0, 0)
}
}
pack()
centerOnScreen()
open()
}
(注意:PopupMenu
已添加到Scala 2.11;之前必须使用第三方包装器,例如ScalaSwingContrib中的第三方包装器。)
否则,您可能只是打开第二个窗口或对话框:
val cb1 = new CheckBox("Foo")
val cb2 = new CheckBox("Bar")
val message = new BoxPanel(Orientation.Vertical) {
contents += cb1
contents += cb2
}
val res = Dialog.showConfirmation(message = message.peer,
optionType = Dialog.Options.OkCancel)
val info = if (res == Dialog.Result.Yes)
s"Foo? ${cb1.selected}; Bar? ${cb2.selected}"
else
"Cancelled"
println(info)
动态更改Swing容器的内容有点烦人。您必须从容器的内容中添加和删除内容,然后重新验证它:
var expanded = false
val cb = new CheckBox("Foo")
new Frame { frame =>
contents = new BoxPanel(Orientation.Vertical) { box =>
contents += new Button("Expand") {
preferredSize = preferredSize // so it doesn't change with the label
listenTo(this)
reactions += {
case event.ButtonClicked(_) =>
expanded = !expanded
if (expanded) {
text = "Hide"
box.contents += cb
} else {
text = "Expand"
box.contents.remove(1)
}
box.revalidate()
frame.pack()
}
}
}
pack()
centerOnScreen()
open()
}