2014-02-17 95 views
0

我正在看Scala中的步驟6.9中的例子,並且他的設置背景的方法不足,因爲當框架被調整大小時,背景不會改變。示例代碼(更新更改到2.10版本的工作是:如何在Scala swing中設置背景

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(矩形)...)爲在上面的註釋,它編譯,但不起作用。

有人建議可以以正確的方式做到這一點?

在此先感謝。

回答

3

最簡單的辦法就是讓鞦韆做背景繪畫

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 
    } 
    }