In sca开发者_如何转开发la.swing, I can add a component to a container like so:
new Frame {
contents += label
}
but sometimes I'd like to clear the contents of a container and replace them with new components. Based on the docs, I should be able to do:
frame.contents.remove(0)
or
frame.contents.clear
but neither of those compile ("clear/remove is not a member of Seq[scala.swing.Component]").
How can I resolve this? Also, it seems that I can't call frame.contents += blah
after intialization. If this is so, how do I add a new component to a Container?
If you're talking about Frame
specifically, you can only add one item, so use the method
def contents_= (c: Component) : Unit
and you should be good. Try this out in the REPL (one line at a time so you can see what's going on):
import scala.swing._
val f = new Frame { contents = new Label("Hi") }
f.visible = true
f.contents = new Label("Hey there")
If you're using something that is intended to have multiple items like a BoxPanel
, contents
is a Buffer
so you can add to it and remove from it:
val bp = new BoxPanel(Orientation.Vertical)
val (label1,label2) = (new Label("Hi"), new Label("there"))
bp.contents += label1
bp.contents += label2
f.contents = bp // Now you see "Hi" "there" stacked
bp.contents -= label1
f.pack // "Hi" disappears--need pack not repaint to fix layout
bp.contents += label1
f.pack // "Hi" is back, but at the end
If you have something else like a Component
that you're extending, it is your job to override contents
with a buffer or have some other way of modifying it (or inherit from SequentialContainer
as J-16 said).
contents
in Container
was a Seq[]
;
you need a SequentialContainer
for that remove method.
精彩评论