headius (owner)

Revisions

gist: 228652 Download_button fork
public
Public Clone URL: git://gist.github.com/228652.git
Embed All Files: show embed
app.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
require 'griffon'
 
swing.frame("Hello", size: [300,300]) do
  panel do
    label('hello', id: 'label')
    button("Press me!",
        id: 'mybutton',
        actionListener: ->{view.mybutton.text = 'Wahoo!'},
        actionListener: ->{view.label.text = 'You pressed it!'}) do
      font(font.derive_font(24.0))
      foreground(color(:red))
    end
  end
end
griffon.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
require 'java'
require 'ostruct'
 
def swing
  SwingBuilder.new
end
 
class String
  def firstcap
    replace(self[0,1].upcase + self[1..-1])
  end
end
 
def color(name)
  java.awt.Color.const_get(name.to_s.upcase)
end
 
class SwingBuilder
  JClass = java.lang.Class
  
  def initialize
    @self_stack = []
    @components = OpenStruct.new
  end
  def method_missing(name, *args, &block)
    inits = nil
    if args[-1].kind_of? Hash
      inits = args.pop
    end
    
    clsname = "javax.swing.J#{name.to_s.firstcap}"
    cls = JClass.for_name clsname rescue nil
    
    if cls
      obj = eval("javax.swing.J#{name.to_s.firstcap}").new(*args)
      unless @self_stack.empty?
        @self_stack[0].add obj
      end
      @self_stack.unshift obj
      if inits
        inits.each do |k,v|
          cap_prop = k.to_s.firstcap
          if k == :id
            eval "@components.#{v} = obj"
          elsif obj.respond_to? "set#{cap_prop}"
            eval "obj.set#{cap_prop}(*v)"
          elsif obj.respond_to? "add#{cap_prop}"
            eval "obj.add#{cap_prop}(*v)"
          else
            raise "Unrecognized property: #{k} on #{obj.class}"
          end
        end
      end
    
      instance_exec(obj, &block) if block
    
      @self_stack.shift
      if @self_stack.empty?
        obj.show
      end
    else
      obj = @self_stack[0]
      if !args.empty? && obj.respond_to?("#{name}=")
        obj.send "#{name}=", *args, &block
      elsif obj.respond_to? name
        obj.send name, *args, &block
      end
    end
  end
  
  def view
    @components
  end
end