问题
I have this Class extending FlowPanel
and I'm trying to add Labels into it:
import java.awt.{Label, Color}
import scala.swing._
import scala.util.Random
class MyPanel extends FlowPanel{
val dimension = new Dimension(600,400)
maximumSize = dimension
minimumSize = dimension
preferredSize = dimension
foreground = Color.white
background = Color.LIGHT_GRAY
def drowLabels(size: Int) = {
for(i <- 0 until size){
contents += new Label()
revalidate();
repaint();
}
}
But I get an error message:
type mismatch;
found : java.awt.Label
required: scala.swing.Component
contents += new Label()
^
But for example if I change new Label()
to new Button()
, everything works fine. Actually I can't add Label
to any kind of container, there are always some errors.
I have been trying to find answer for an hour, but without succeed.
回答1:
I think the message is telling you that a SWING component is expected which java.awt.Label
is not (look at your imports). The SWING label is javax.swing.JLabel, so fixing the imports as follows should solve your problem:
import java.awt.Color
import javax.swing.JLabel
import scala.swing._
import scala.util.Random
class MyPanel extends FlowPanel {
...
def drowLabels(size: Int) = {
for(i <- 0 until size){
contents += new JLabel()
revalidate();
repaint();
}
}
回答2:
It appears that the above solution no longer works: scala swing containers will not allow you to add elements unless they inherit from scala.swing.Component
class. Therefore, one has to either use components from scala swing or wrap Java components with Component.wrap(javaSwingComponent)
call.
See this question for more details.
来源:https://stackoverflow.com/questions/27621939/type-mismatch-error-when-adding-label-to-scala-swing-panel