Project: Scribble
Step 1 Paint Rectangle
import java.awt.{Color, Graphics2D}
import scala.swing.BorderPanel.Position.Center
import scala.swing.{BorderPanel, Dimension, MainFrame, Panel, SimpleSwingApplication}
object Scribble1 extends SimpleSwingApplication:
def top = new MainFrame:
title = "Scribble App"
object canvas extends Panel:
override def paintComponent(g: Graphics2D): Unit =
super.paintComponent(g)
g.setColor(Color.black)
g.drawRect(20, 20, 20, 20)
contents = new BorderPanel:
layout(canvas) = Center
size = new Dimension(500, 500)
step 2 Mouse Events
add the mouse events to the canvas
object canvas extends Panel:
listenTo(mouse.clicks)
var x1 = 0
var y1 = 0
var x2 = 0
var y2 = 0
reactions +=
case e: MousePressed =>
x1 = e.point.x
y1 = e.point.y
case e: MouseReleased =>
x2 = e.point.x
y2 = e.point.y
repaint()
step 3: Rectangle class
class Rect(var x1: Int, var y1: Int, var x2: Int, var y2: Int):
def draw(g: Graphics2D): Unit =
g.drawRect(x1, y1, x2 - x1, y2 - y1)
step 4 Shape trait
trait Shape:
var x1: Int
var y1: Int
var x2: Int
var y2: Int
def draw(g: Graphics2D): Unit
Also create an Oval class
step 5 More shapes
private val shapes: ListBuffer[Shape] = ListBuffer()
case e: MousePressed =>
if e.triggersPopup then
shp = Oval(e.point.x, e.point.y, 0, 0)
else
shp = Rect(e.point.x, e.point.y, 0, 0)
shapes.append(shp)
step 6 Button Panel
val modePanel = new FlowPanel:
val rectangleButton = new Button("Rectangle")
val ovalButton = new Button("Oval")
contents += rectangleButton
contents += ovalButton
listenTo(rectangleButton, ovalButton)
reactions += {
case ButtonClicked(`rectangleButton`) => currentMode = Rectangle
case ButtonClicked(`ovalButton`) => currentMode = Oval
}
// backticks: In pattern matching, it helps you to use variable as if its a concrete value.