Skip to content

Instantly share code, notes, and snippets.

@jingjiecb
Last active May 5, 2023 17:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jingjiecb/e3c049ea6e463d9f06a45e879ea0878a to your computer and use it in GitHub Desktop.
Save jingjiecb/e3c049ea6e463d9f06a45e879ea0878a to your computer and use it in GitHub Desktop.
PaintingDsl的测试脚本和定义脚本
package top.claws.dsl
import javax.swing.JFrame
import javax.swing.JPanel
import java.awt.Color
import java.awt.Graphics
/**
* @author claws
* @since 2023/5/5
*/
class PaintingDsl {
def sizeMap = [:]
def lineList = []
def curColor = colorMap.black
static colorMap = [
red : new Color(255, 175, 175),
black: new Color(0, 0, 0),
white: new Color(255, 255, 255)
]
PaintingDsl(length, width) {
sizeMap.length = length
sizeMap.width = width
}
static def pad(def length, def width, Closure closure) {
def dsl = new PaintingDsl(length, width)
closure.delegate = dsl
closure.resolveStrategy = Closure.DELEGATE_ONLY
closure()
dsl.show()
}
static def pad(Closure closure) {
pad(500, 500, closure)
}
def size(Closure closure) {
println "changing size..."
sizeMap.with closure
}
def show() {
println "showing..."
def panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g)
for (def line in lineList) {
g.setColor(line.color)
g.drawLine(line.xFrom, line.yFrom, line.xTo, line.yTo)
}
}
}
def frame = new JFrame()
frame.contentPane = panel
frame.setSize(sizeMap.length, sizeMap.width)
frame.setLocationRelativeTo(null)
frame.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
frame.visible = true
}
def line(Closure closure) {
def dsl = new LineDsl(this)
closure.delegate = dsl
closure.resolveStrategy = Closure.DELEGATE_ONLY
closure()
}
def color(String color) {
curColor = colorMap[color]
}
}
class LineDsl {
def paintingDsl
def lineBuilding
LineDsl(def paintingDsl) {
this.paintingDsl = paintingDsl
}
def start(x, y) {
lineBuilding = new Line()
lineBuilding.xFrom = x
lineBuilding.yFrom = y
this
}
def end(x, y) {
lineBuilding.xTo = x
lineBuilding.yTo = y
lineBuilding.color = paintingDsl.curColor
paintingDsl.lineList.add(lineBuilding)
lineBuilding = null
}
}
class Line {
def xFrom
def yFrom
def xTo
def yTo
def color
}
import static top.claws.dsl.PaintingDsl.*
pad(500, 500) {
color "black"
line {
start(100, 200) end(300, 300)
start(100, 30) end(0, 0)
}
color "red"
line {
start(100, 200) end(100, 300)
start(500, 500) end(60, 20)
}
}
pad {
size {
length = 1000
width = 1000
}
color "red"
line {
start(100, 200) end(300, 300)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment