Swing 从scala访问java.awt.Container.getComponents
我正在尝试为一个用scala和swing编写的gui应用程序编写自动化测试。我正在修改代码,利用这些代码在树中找到正确的ui元素 这是我的代码的独立版本。它是不完整的、未经测试的,可能在各种方面都是不完整的和/或非惯用的和/或次优的,但我的问题是关于下面列出的编译器错误Swing 从scala访问java.awt.Container.getComponents,swing,unit-testing,scala,Swing,Unit Testing,Scala,我正在尝试为一个用scala和swing编写的gui应用程序编写自动化测试。我正在修改代码,利用这些代码在树中找到正确的ui元素 这是我的代码的独立版本。它是不完整的、未经测试的,可能在各种方面都是不完整的和/或非惯用的和/或次优的,但我的问题是关于下面列出的编译器错误 import scala.swing._ import java.awt._ import ListView._ import org.scalatest.junit.JUnitRunner import org.junit.
import scala.swing._
import java.awt._
import ListView._
import org.scalatest.junit.JUnitRunner
import org.junit.runner.RunWith
import org.scalatest.FunSpec
import org.scalatest.matchers.ShouldMatchers
object MyGui extends SimpleSwingApplication {
def top = new MainFrame {
title = "MyGui"
val t = new Table(3, 3)
t.peer.setName("my-table")
contents = t
}
}
object TestUtils {
def getChildNamed(parent: UIElement, name: String): UIElement = {
// Debug line
println("Class: " + parent.peer.getClass() +
" Name: " + parent.peer.getName())
if (name == parent.peer.getName()) { return parent }
if (parent.peer.isInstanceOf[java.awt.Container]) {
val children = parent.peer.getComponents()
/// COMPILER ERROR HERE ^^^
for (child <- children) {
val matching_child = getChildNamed(child, name)
if (matching_child != null) { return matching_child }
}
}
return null
}
}
@RunWith(classOf[JUnitRunner])
class MyGuiSpec extends FunSpec {
describe("My gui window") {
it("should have a table") {
TestUtils.getChildNamed(MyGui.top, "my-table")
}
}
}
,getComponents实际上是java.awt.Component的成员。我曾经在parent.peer
上转储方法,我可以看到getComponents在列表中
欢迎提供解决问题的另一种方法(类似方式的自动gui测试)的答案,但我真的很想理解为什么我不能访问getComponents。问题是您正在查看两个不同的类。您的javadoc链接指向
java.awt.Container
,它确实有getComponents
方法。另一方面,编译器正在java.awt.Component
(父类)上查找getComponents
,它是由parent.peer
返回的,但找不到它
如果(parent.peer.isInstanceOf[java.awt.Container])…,您可以验证parent.peer的类型并按如下方式强制转换它:
parent.peer match {
case container: java.awt.Container =>
// the following works because container isA Container
val children = container.getComponents
// ...
case _ => // ...
}
啊,我一定看了20遍了,没发现是另外一门课。谢谢
parent.peer match {
case container: java.awt.Container =>
// the following works because container isA Container
val children = container.getComponents
// ...
case _ => // ...
}