Type mismatch error when adding JLabel/JPanel to S

2019-09-18 07:45发布

问题:

I'm trying to incorporate a java native JLabel (or a JPanel) to a scala swing application and I'm stuck with the compile error.

The code I'm trying to run is the following.

package com.david

import javax.swing.JPanel

import scala.swing._

object Hello extends SimpleSwingApplication {

  def top = new MainFrame {
    title = "First Swing App"

    contents = new JPanel()
  }
}

The compiler gives me the following error.

$ sbt compile
[info] Set current project to MyGui (in build file:/home/david/programming/scala/MyGui/)
[info] Compiling 1 Scala source to /home/david/programming/scala/MyGui/target/scala-2.11/classes...
[error] /home/david/programming/scala/MyGui/src/main/scala/com/david/Hello.scala:12: type mismatch;
[error]  found   : javax.swing.JPanel
[error]  required: scala.swing.Component
[error]     contents = new JPanel()
[error]                ^
[error] one error found
[error] (compile:compileIncremental) Compilation failed
[error] Total time: 3 s, completed Apr 10, 2015 12:13:11 PM

Also, here is my build.sbt file:

name := "MyGui"

version := "1.0"

scalaVersion := "2.11.6"

libraryDependencies += "org.scala-lang.modules" %% "scala-swing" % "1.0.1"

The system is the following.

$ java -version
java version "1.7.0_76"
Java(TM) SE Runtime Environment (build 1.7.0_76-b13)
Java HotSpot(TM) 64-Bit Server VM (build 24.76-b04, mixed mode)
$ uname -a
Linux strela 3.13.0-48-generic #80-Ubuntu SMP Thu Mar 12 11:16:15 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux

I know that people have had similar problems, but this is different -- I'm using the correct components (JLabel/JPanel instead of Label/Panel).

回答1:

Scala swing uses a thin wrapper component abstraction where the scala.swing.Component base class wraps Java swing components rather than being a part of their class hierarchy.

This means you must either use Panel/Label from scala swing, or use Component.wrap(javaSwingComponent) to make java swing components it into a scala swing components that can be used together with other scala swing components.