// // program to demonstrate a little of the functionality needed for a drawing // program: controlling what is drawn on screen, responding to mouse and // keyboard input // // click and drag to draw a rectangle, type 'c' to clear // import scala.swing._ import scala.swing.event._ import java.awt.Color import java.awt.Graphics2D // point where user pressed mouse button (-1 for none) // (Point is in scala.swing) // (we probably should use "null" for none but we don't know about that yet) var startPoint = new Point(-1, -1) // point where user released mouse button (-1 for none) var endPoint = new Point(-1, -1) // current "drag" point (-1 for none) var dragPoint = new Point(-1, -1) // get rectangle defined by two points // (Rectangle is in scala.swing) def pointsToRectangle(p1 : Point, p2 : Point) : Rectangle = { val left = p1.x min p2.x val top = p1.y min p2.y val w = math.abs(p1.x - p2.x) val h = math.abs(p1.y - p2.y) new Rectangle(left, top, w, h) } // panel for drawing val drawingPanel = new Panel { override def paint(g : Graphics2D) { g.setPaint(Color.WHITE) // clear background g.fill(new Rectangle(0,0,size.width,size.height)) g.setPaint(Color.GREEN) // "fill" completed rectangle if ((startPoint.x != -1) && (endPoint.x != -1)) { g.fill(pointsToRectangle(startPoint, endPoint)) } // draw outline of rectangle in progress if ((startPoint.x != -1) && (dragPoint.x != -1)) { g.draw(pointsToRectangle(startPoint, dragPoint)) } } listenTo(mouse.clicks,mouse.moves,keys) reactions += { case e:MousePressed => requestFocus() // only needed because we have keyboard input too startPoint = e.point endPoint = new Point(-1, -1) dragPoint = new Point(-1, -1) repaint() case e:MouseReleased => requestFocus() // only needed because we have keyboard input too endPoint = e.point dragPoint = new Point(-1, -1) repaint() case e:MouseDragged => requestFocus() // only needed because we have keyboard input too dragPoint = e.point repaint() case e:KeyTyped => requestFocus() // only needed because we have keyboard input too if (e.char == 'c') { startPoint = new Point(-1, -1) endPoint = new Point(-1, -1) dragPoint = new Point(-1, -1) } repaint() } } // main layout val frame = new MainFrame { title = "Drawing Program Prototype" contents = new BorderPanel { layout += (drawingPanel -> BorderPanel.Position.Center) } size = new Dimension(400,400) } // start up frame.visible = true