Scribble demo

From Erights

Jump to: navigation, search

This is a simple demo of drawing and event handling in an AWT window from E.

#!/usr/bin/env rune

pragma.syntax("0.9")

# --- init

currentVat.morphInto("awt")

# --- definitions

def makeEPainter := <unsafe:com.zooko.tray.makeEPainter>

/** protection against throwing out of an AWT callback and getting a useless backtrace */
def catching(inner) {
  def catcher match msg {
    try {
      E.callWithPair(inner, msg)
    } catch p {
      stderr.println(`$p${p.eStack()}`)
      null
    }
  }
  return catcher
}

def makeScribbleComponent(model) {
   var x := 0
   var y := 0

   def scribbleC := makeEPainter(catching(def painter {
     to paintComponent(g) {
       for line :Tuple[int, int, int, int] in model {
         E.call(g, "drawLine", line)
       }
     }
   }))

   scribbleC.addMouseListener(catching(def ml {
     to mousePressed(event) {
       x := event.getX()
       y := event.getY()
     }
     match _ {}
   }))

   scribbleC.addMouseMotionListener(catching(def mml {
     to mouseDragged(event) {
       model.push([x, y,
                   x := event.getX(),
                   y := event.getY()])
       scribbleC.repaint()
     }
     match _ {}
   }))
   
   scribbleC.setPreferredSize(<awt:makeDimension>(300, 300))
   return scribbleC
}

# --- application

def lines := [].diverge()
def done

def frame := <unsafe:javax.swing.makeJFrame>("Scribble")
frame.setContentPane(makeScribbleComponent(lines))

frame.addWindowListener(catching(def mainWindowListener {
   to windowClosing(event) :void {
     bind done := null
   }
   match _ {}
}))

frame.setLocation(50, 50)
frame.pack()
frame.show()

interp.waitAtTop(done)
Personal tools
more tools