简体   繁体   English

将标签添加到Scala Swing面板时出现类型不匹配错误

[英]Type mismatch error when adding Label to Scala Swing Panel

I have this Class extending FlowPanel and I'm trying to add Labels into it: 我有扩展FlowPanel并且我试图在其中添加标签:

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. 但是例如,如果我将new Label()更改为new Button() ,则一切正常。 Actually I can't add Label to any kind of container, there are always some errors. 实际上,我无法将Label添加到任何类型的容器中,总是会出现一些错误。

I have been trying to find answer for an hour, but without succeed. 我一直在寻找答案一个小时,但没有成功。

I think the message is telling you that a SWING component is expected which java.awt.Label is not (look at your imports). 我认为该消息告诉您期望使用SWING组件,而java.awt.Label则不是(请查看您的导入)。 The SWING label is javax.swing.JLabel , so fixing the imports as follows should solve your problem: SWING标签为javax.swing.JLabel ,因此按以下方式修复导入应该可以解决您的问题:

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();
         }
    }

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. 看来上述解决方案不再起作用:scala swing容器将不允许您添加元素,除非它们从scala.swing.Component类继承。 Therefore, one has to either use components from scala swing or wrap Java components with Component.wrap(javaSwingComponent) call. 因此,必须使用scala swing中的组件或通过Component.wrap(javaSwingComponent)调用包装Java组件。

See this question for more details . 有关更多详细信息,请参见此问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM