Skip to content

…Must…Resist…JRuby…Scribble…

I am weak-willed, I admit it! A JRuby version of Scribble!

require 'java'

include_class 'java.awt.event.MouseAdapter'
include_class 'java.awt.event.MouseMotionAdapter'
include_class 'javax.swing.JPanel'
include_class 'javax.swing.JFrame'
include_class 'java.awt.Graphics'
include_class 'java.awt.Color'

$model = Array.new

$last_x = 0
$last_y = 0

class MouseAction < MouseAdapter
  def mousePressed(e)
    $last_x = e.x
    $last_y = e.y
  end
end

class DrawLine
  def initialize(x0, y0, x1, y1)
    @x0 = x0
    @y0 = y0
    @x1 = x1
    @y1 = y1
  end

  def paint(g)
    g.drawLine(@x0, @y0, @x1, @y1)
  end
end

class MouseMotionAction < MouseMotionAdapter
  def mouseDragged(e)
    g = e.component.graphics
    x = e.x
    y = e.y
    g.setColor(Color.black)
    d = DrawLine.new($last_x, $last_y, x, y)
    $model << d
    d.paint(g)
    $last_x = x
    $last_y = y
  end
end

class Scribble < JPanel
  def paint(g)
    $model.each {  | it | it.paint(g) }
  end
end

class MainWindow < JFrame
  def initialize
    super "JRuby Scribble"
    setDefaultCloseOperation JFrame::EXIT_ON_CLOSE
    setSize(600,400)
    setResizable(false)
    panel = Scribble.new
    panel.addMouseListener MouseAction.new
    panel.addMouseMotionListener MouseMotionAction.new
    add panel
  end
end

MainWindow.new.setVisible true

Surprisingly, I couldn’t find one of these out there on the ‘web, so this is All My Own Work :-)

I wrote it using the JRuby implementation shipped with Netbeans 6.7m3.

I have to say, I found the ‘@’, ‘$’ stuff pretty irritating, but I guess a Perl guy would feel at home (hmmm…is this a good thing….hmmmmm)

Java Enterprise Edition, JEE, JavaServer Pages, JSP, Tag Libraries, Servlets, Enterprise Java Beans, EJB, Java Messaging Service JMS, BEA Weblogic, JBoss, Application Servers, Spring Framework, Groovy, Grails, Griffon, Seam, Open Source, Service Oriented Architectures, SOA, Java 2 Standard Edition, J2SE