我正在查看Scala中的步骤中的示例6.9,并且他设置背景的方法不合适,因为调整帧的大小时,背景不会改变。示例代码(针对版本2.10的更改进行了更新:
import scala.swing._
import scala.swing.event._
object circle extends SimpleSwingApplication {
def top = new MainFrame {
var mouseX = 0
var mouseY = 0
var mouseclicked = false
title = "Draw Circle"
val rect = new java.awt.Rectangle(350,250)
preferredSize = new Dimension(350,250)
val canvas = new Panel {
border = Swing.EmptyBorder(15, 15, 15, 15)
opaque = false
override def paintComponent(g: java.awt.Graphics2D) {
// g.setBackground(java.awt.Color.magenta)
g.setColor(java.awt.Color.magenta)
g.fill(rect)
g.setColor(java.awt.Color.blue)
if ( mouseclicked ) {
g.fillOval(mouseX-10, mouseY-10, 20, 20)
mouseclicked = false
}
}
listenTo(mouse.clicks)
reactions += {
case MouseClicked(_, p, _, 1, _) => {
mouseX = p.x
mouseY = p.y
mouseclicked = true
repaint
}
}
}
contents = canvas
}
}
我尝试用g.setBackground(...)替换g.setColor(...)和g.fill(rect),如上所述,它编译但不起作用。
有人可以建议正确的方法吗?
提前致谢。
答案 0 :(得分:3)
简单的方法是让Swing做背景画
val canvas = new Panel {
opaque = true
background = Color.magenta
override def paintComponent(g: java.awt.Graphics2D) {
super.paintComponent(g);
g.setColor(Color.blue)
if (mouseclicked) {
g.fillOval(mouseX - 10, mouseY - 10, 20, 20)
mouseclicked = false
}
}