这一篇我们来结束一下之前构造的DSL吧。
其实本来我还想继续构建下去的,但是被几个朋友吐槽说很丑,所以还是算了吧……不过我倒是挺喜欢这种流插入风格的
嗯,这里是我们的测试程序现在目前的状态
class Test extends SApplication {
def start(primaryStage: Stage) {
nSButton <<
Name << "btn" <<
Type << SButton <<
OnAction << println("Hello World") <<
Text << "Hello World!"
val root = new StackPane
root.getChildren.add("btn" :: SButton)
val scene = new Scene(root, 300, 250)
primaryStage <<
Title << "Hello World!" <<
IStage.Scene << scene << Show
}
}
可以看到,下端的部分也变成了流插入的风格。或许有朋友会疑惑,为什么我们能在Stage类的对象上调用<<方法?其实很简单,这里我们用到了一个隐式转换` implicit def stage2istage(stage: Stage) = new IStage(stage)
,把Stage对象转换成我们自定义的IStage类对象,然后调用IStage对象的<<方法。
package sjavafx.stage
import javafx.scene.Scene
import javafx.stage.Stage
import sjavafx.Insertable
import sjavafx.application.SApplication
import sjavafx.application.SApplication.IStage._
/**
* Created by Administrator on 2016/10/5.
*/
class IStage(val stage: Stage) extends Insertable {
def <<(t:Title.type ) = new In{
def <<(str:String) = {
s.setTitle(str)
Is
}
}
def <<(t:SApplication.IStage.Scene.type ) = new In{
def <<(sc:Scene) = {
s.setScene(sc)
Is
}
}
def <<(show:Show.type ) = {
stage.show()
stage
}
class In(val Is: IStage = this ,val s: Stage = stage)
}
现在,我们的DSL构建也告一段落,下一篇我们就要回到正常的JavaFX学习中了。