Skip to content

Instantly share code, notes, and snippets.

@timyates
Created June 23, 2012 19:03
Show Gist options
  • Select an option

  • Save timyates/2979500 to your computer and use it in GitHub Desktop.

Select an option

Save timyates/2979500 to your computer and use it in GitHub Desktop.
SwingBuilder rendering to background of the JScrollPane that the code is written in
import groovy.swing.*
import java.awt.*
import javax.swing.*
import javax.swing.event.*
import org.codehaus.groovy.control.customizers.ImportCustomizer
import org.codehaus.groovy.control.CompilerConfiguration
String script = '''color = Color.RED
|fillRect 10, 10, 100, 100'''.stripMargin()
class RenderingViewport extends JViewport {
GroovyShell shell = new GroovyShell( this.class.classLoader )
Closure painter = null
RenderingViewport() {
def importCustomizer = new ImportCustomizer()
importCustomizer.addStarImports( 'java.awt', 'java.awt.geom' )
def configuration = new CompilerConfiguration()
configuration.addCompilationCustomizers(importCustomizer)
shell = new GroovyShell(configuration)
}
void change( text ) {
try {
painter = shell.evaluate( "{ g -> g.with { $text } }" ) ; repaint()
} catch( e ) {
}
}
void paintChildren( Graphics g ) {
if( painter ) try { painter( g ) } catch( e ) {}
super.paintChildren( g )
}
}
new SwingBuilder().frame( size:[ 800, 600 ], show:true, title:'Painter' ) {
panel( layout: new BorderLayout() ) {
new RenderingViewport().with { vp ->
textArea( id:'editor', opaque:false ).with { ta ->
vp.view = ta
scrollPane().with {
viewport = vp
}
def listener = [ insertUpdate: { edt { vp.change( ta.text ) } },
removeUpdate: { edt { vp.change( ta.text ) } },
changedUpdate:{ edt { vp.change( ta.text ) } } ] as DocumentListener
ta.document.addDocumentListener listener
ta.text = script
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment