plataforma javafx 2.0, groovyfx, scalafx e visage

73
Plataforma JavaFX 2.0, GroovyFX, ScalaFX e Visage Stephen Chin Chefe de metodologias Ageis, GXS [email protected] tweet: @steveonjava Translated by Marcelo Quinta

Upload: gustavo-luis-condoy-pogo

Post on 24-Nov-2015

61 views

Category:

Documents


2 download

TRANSCRIPT

09J1 template, PPT2008/Macintosh

Plataforma JavaFX 2.0, GroovyFX, ScalaFX e VisageStephen ChinChefe de metodologias Ageis, [email protected]: @steveonjavaTranslated by Marcelo Quinta1Conheca o palestranteStephen Chinhttp://steveonjava.com/

MotorcyclistFamily ManJava ChampionAutorPro JavaFX PlatformPro Android FlashFundador de projetos Open SourceJFXtrasScalaFXWidgetFXVisage2A plataforma JavaFX 2.0Experiencia imersiva Desktop combinando o melhor do JavaFX e HTML5Use seus conhecimentos Java com as modernas APIs JavaFXIntegre Java, JavaScript e HTML5 na mesma aplicacaoNova gama de graficos usa as vantagens de aceleracao de hardware para aplicacoes 2D e 3DUse sua IDE favorita: NetBeans, Eclipse, IntelliJ, etc.

3JavaFX agora e Open Source!Parte do projeto OpenJDK

Controles disponiveis agoracodigo adicional adicionado incrementalmente

Pagina do projeto:http://openjdk.java.net/projects/openjfx/4

E vai rodar nos Tablets!5iPad (iOS)Linux (plataforma popular que executa algo semelhante a Java)

Nenhuma data de release foi anunciadaConstruindo Aplicacoes JavaFXPode ser executada no navegador ou no DesktopInclui builders para construcoes declarativasLinguagens alternativas tambem podem ser utilizadas para simplificar a criacao da interface de usuarioGroovyFXScalaFXVisage67Ola JUG (Versao Java)public class HelloJUG extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { primaryStage.setTitle("Ola JUG"); Group root = new Group(); Scene scene = new Scene(root, 400, 250, Color.ALICEBLUE); Text text = new Text(); text.setX(105); text.setY(120); text.setFont(new Font(30)); text.setText("Ola JUG"); root.getChildren().add(text); primaryStage.setScene(scene); primaryStage.show(); }}8Ola JUG (Versao com o Builder)public void start(Stage primaryStage) { primaryStage.setTitle("Ola JUG"); primaryStage.setScene(SceneBuilder.create() .width(400) .height(250) .fill(Color.ALICEBLUE) .root( GroupBuilder.create().children( TextBuilder.create() .x(105) .y(120) .text("Ola JUG") .font(new Font(30)) .build() ).build() ) .build()); primaryStage.show();}9Ola JUG (Versao GroovyFX)GroovyFX.start { primaryStage -> def sg = new SceneGraphBuilder() sg.stage( title: 'Ola JUG', show: true) { scene( fill: aliceblue, width: 400, height: 250) { text( x: 105, y: 120, text: "Ola JUG" font: "30pt") } }}10Ola JUG (Versao JavaFX)object HelloJUG extends JFXApp { stage = new Stage { title = "Ola JUG" width = 400 height = 250 scene = new Scene { fill = BLUE Text { x = 105 y = 120 text = "Ola JUG" font = Font(size: 30) } } }}11Ola JUG (Versao Visage)Stage { title: "Ola JUG" width: 400 height: 250 scene: Scene { fill: BLUE content: Text { x: 105 y: 120 text: "Ola JUG" font: Font {size: 30pt} } }}Mostrando HTML no JavaFXpublic class WebViewTest extends Application { public static void main(String[] args) { launch(WebViewTest.class, args); } @Override public void start(Stage stage) { WebView webView = new WebView(); webView.getEngine().load("http://google.com"); Scene scene = new Scene(webView); stage.setScene(scene); stage.setTitle("Web Test"); stage.show();}}12Mostrando HTML no JavaFX

13Chamando Javascript pelo JavaFXString script = "alert('Aooo Goiania!');;eng.executeScript(script);14Respondendo a eventos do browserEventos suportados:Alert/Confirm/Prompt:Responda funcoes do Javascript de interacao do usuarioResize:Web page move-se ou rearranja ao tamanho da janelaStatusWeb page muda o texto do statusVisibilityEsconde ou mostra algum objeto da janelaPopupCria uma segunda janela15Demo de integracao HTML5/JavaFX16

JavaFX com Groovy

17Features of GroovyLinguagem modernaClosuresTransforms ASTLinguagem fortemente tipada

Grande integracao com JavaMuito facil fazer a portabilidade de Java para Groovy

Sintaxe declarativa com builders GroovyFXFamiliar aos desenvolvedores Groovy e JavaFX Script

18Java vs. GroovyFX DSLpublic class HelloStage extends Application {

public void start(Stage stage) { stage.setTitle("Hello Stage"); stage.setWidth(600); stage.setHeight(450); Scene scene = new Scene(); scene.setFill(Color.LIGHTGREEN); Rectangle rect = new Rectangle(); rect.setX(25); rect.setY(40); rect.setWidth(100); rect.setHeight(50); rect.setFill(Color.RED); scene.setRoot(new Group(rect)); stage.setScene(scene); stage.show(); }

public static void main(String[] args) { launch(HelloStage.class, args); }}GroovyFX.start { stage -> def sg = new SceneGraphBuilder(stage)

sg.stage(title: Hello Stage, width: 600, height: 450) { scene(fill: groovyblue) { rectangle(x: 25, y: 40, width: 100, height: 50, fill: red) } }}

1921 Linhas430 Caracteres8 Linhas180 Caracteres19def sg = new SceneGraphBuilder()def hc = { hover -> hover ? 4 : 0 }

sg.stage(title: 'Vanishing Circles', show: true) { scene(fill: black, width: 800, height: 600) { 50.times { circle(centerX: rand(800), centerY: rand(600), radius: 150, stroke: white, strokeWidth: bind('hover', converter: hc)) { fill rgb(rand(255), rand(255), rand(255), 0.2) effect boxBlur(width: 10, height: 10, iterations: 3) } } }}202021def sg = new SceneGraphBuilder()def hc = { hover -> hover ? 4 : 0 }

sg.stage(title: 'Vanishing Circles', show: true) { scene(fill: black, width: 800, height: 600) { 50.times { circle(centerX: rand(800), centerY: rand(600), radius: 150, stroke: white, strokeWidth: bind('hover', converter: hc)) { fill rgb(rand(255), rand(255), rand(255), 0.2) effect boxBlur(width: 10, height: 10, iterations: 3) } } }}Builder para Scene Graphs do GroovyFX2122def sg = new SceneGraphBuilder()def hc = { hover -> hover ? 4 : 0 }

sg.stage(title: 'Vanishing Circles', show: true) { scene(fill: black, width: 800, height: 600) { 50.times { circle(centerX: rand(800), centerY: rand(600), radius: 150, stroke: white, strokeWidth: bind('hover', converter: hc)) { fill rgb(rand(255), rand(255), rand(255), 0.2) effect boxBlur(width: 10, height: 10, iterations: 3) } } }}Definicao declarativa do Stage2223def sg = new SceneGraphBuilder()def hc = { hover -> hover ? 4 : 0 }

sg.stage(title: 'Vanishing Circles', show: true) { scene(fill: black, width: 800, height: 600) { 50.times { circle(centerX: rand(800), centerY: rand(600), radius: 150, stroke: white, strokeWidth: bind('hover', converter: hc)) { fill rgb(rand(255), rand(255), rand(255), 0.2) effect boxBlur(width: 10, height: 10, iterations: 3) } } }}Definicao de propriedades embutdidas2324def sg = new SceneGraphBuilder()def hc = { hover -> hover ? 4 : 0 }

sg.stage(title: 'Vanishing Circles', show: true) { scene(fill: black, width: 800, height: 600) { 50.times { circle(centerX: rand(800), centerY: rand(600), radius: 150, stroke: white, strokeWidth: bind('hover', converter: hc)) { fill rgb(rand(255), rand(255), rand(255), 0.2) effect boxBlur(width: 10, height: 10, iterations: 3) } } }}Bind para propriedades2425def sg = new SceneGraphBuilder()def hc = { hover -> hover ? 4 : 0 }

sg.stage(title: 'Vanishing Circles', show: true) { scene(fill: black, width: 800, height: 600) { 50.times { circle(centerX: rand(800), centerY: rand(600), radius: 150, stroke: white, strokeWidth: bind('hover', converter: hc)) { fill rgb(rand(255), rand(255), rand(255), 0.2) effect boxBlur(width: 10, height: 10, iterations: 3) } } }}Criacao de sequencias via loop25Propriedades em Javapublic class Person { private StringProperty firstName; public void setFirstName(String val) { firstNameProperty().set(val); } public String getFirstName() { return firstNameProperty().get(); } public StringProperty firstNameProperty() { if (firstName == null) firstName = new SimpleStringProperty(this, "firstName"); return firstName; } private StringProperty lastName; public void setLastName(String value) { lastNameProperty().set(value); } public String getLastName() { return lastNameProperty().get(); } public StringProperty lastNameProperty() { if (lastName == null) // etc. } }

2626Propriedades em GroovyFXpublic class Person { @FXBindable String firstName; @FXBindable String lastName;}

2727public class Person { @FXBindable String firstName; @FXBindable String lastName = Smith;}

Propriedades em GroovyFX28Inicializadores opcionais28public class Person { @FXBindable String firstName; @FXBindable String lastName = Smith;}

def p = new Person()def last = p.lastNamep.firstName = Agent

Propriedades em GroovyFX29Valores get and set29public class Person { @FXBindable String firstName; @FXBindable String lastName = Smith;}

def p = new Person()def last = p.lastNamep.firstName = Agent

textField(text: bind(p.lastNameProperty()))

Propriedades em GroovyFX30Acesso a propriedades embutidas para binding30Binding em GroovyFX@FXBindableclass Time { Integer hours Integer minutes Integer seconds

Double hourAngle Double minuteAngle Double secondAngle

public Time() { // bind the angle properties to the clock time hourAngleProperty().bind((hoursProperty() * 30.0) + (minutesProperty() * 0.5)) minuteAngleProperty().bind(minutesProperty() * 6.0) secondAngleProperty().bind(secondsProperty() * 6.0) }}3131Animation em GroovyFXtimeline(cycleCount: Timeline.INDEFINITE, autoReverse: true) { at (1000.ms) { change(rect1, 'x') to 200 tween ease_both change rect2.yProperty() to 200 tween linear }}.play()3232timeline(cycleCount: Timeline.INDEFINITE, autoReverse: true) { at (1000.ms) { change(rect1, 'x') to 200 tween ease_both change rect2.yProperty() to 200 tween linear }}.play()Animation em GroovyFX33Sintaxe facil para animacoes: at (duration) {keyframes}33timeline(cycleCount: Timeline.INDEFINITE, autoReverse: true) { at (1000.ms) { change(rect1, 'x') to 200 change rect2.yProperty() to 200 }}.play()Animation em GroovyFX34Key frame DSL 34timeline(cycleCount: Timeline.INDEFINITE, autoReverse: true) { at (1000.ms) { change(rect1, 'x') to 200 tween ease_both change rect2.yProperty() to 200 tween linear }}.play()Animation em GroovyFX35Controle de velocidade opcional35Event Listeners em GroovyFX36Sintaxe para Closure usando controles embutidosArgumentos opcionais para eventosonMouseClicked { e -> timeline { at(3.s) { change e.source.radiusProperty() to 0 } }.play()}36Event Listeners em GroovyFXSintaxe para Closure usando controles embutidosArgumentos opcionais para eventos37onMouseClicked { MouseEvent e -> timeline { at(3.s) { change e.source.radiusProperty() to 0 } }.play()}Sintaxe compacta{body}37Event Listeners em GroovyFXSintaxe para Closure usando controles embutidosArgumentos opcionais para eventos38Parametros opcionais para eventos{event -> body}onMouseClicked { MouseEvent e -> timeline { at(3.s) { change e.source.radiusProperty() to 0 } }.play()}38TableView em Java39ObservableList items = ...TableView tableView = new TableView(items); TableColumn firstNameCol = new TableColumn("First Name");

firstNameCol.setCellValueFactory( new Callback() { public ObservableValue call(CellDataFeatures p) { return p.getValue().firstNameProperty(); }}); tableView.getColumns().add(firstNameCol);39TableView em GroovyFX40def dateFormat = new SimpleDateFormat("yyyy-MM-dd");

tableView(items: persons) { tableColumn(property: "name", text: "Name", prefWidth: 150) tableColumn(property: "age", text: "Age", prefWidth: 50) tableColumn(property: "gender", text: "Gender", prefWidth: 150) tableColumn(property: "dob", text: "Birth", prefWidth: 150, type: Date, converter: { from -> return dateFormat.format(from) })}40Layout em Java41TextField urlField = new TextField(http://www.google.com);HBox.setHgrow(urlField, Priority.ALWAYS);

HBox hbox = new HBox();hbox.getChildren().add(urlField);

WebView webView = new WebView();VBox.setVgrow(webView, Priority.ALWAYS);

VBox vbox = new VBox();vbox.getChildren().addAll(hbox, webView);41Layout em GroovyFX42sg.stage(title: "GroovyFX WebView Demo", show: true) { scene(fill: groovyblue, width: 1024, height: 800) { vbox { hbox(padding: 10, spacing: 5) { textField(http://www.yahoo.com, hgrow: "always") button("Go) } webView(vgrow: "always") } }}42Layout em GroovyFX43

43Layout em GroovyFX44gridPane(hgap: 5, vgap: 10, padding: 25) { columnConstraints(minWidth: 50, halignment: "right") columnConstraints(prefWidth: 250) label("Send Us Your Feedback", font: "24pt sanserif", row: 0, columnSpan: GridPane.REMAINING, halignment: "center", margin: [0, 0, 10])

label("Name: ", row: 1, column: 0) textField(promptText: "Your name", row: 1, column: 1, hgrow: 'always')

label("Email:", row: 2, column: 0) textField(promptText: "Your email", row: 2, column: 1, hgrow: 'always')

label("Message:", row: 3, column: 0, valignment: "baseline") textArea(row: 3, column: 1, hgrow: "always", vgrow: "always")

button("Send Message", row: 4, column: 1, halignment: "right")}44Layout em GroovyFX45

45

GroovyFX Suporta46

46GroovyFX Suporta47

4748JavaFX Com Scala

48O Que e ScalaComecou em 2001 by Martin OderskyCompila para bytecodes JavaLinguagem puramente orientada a objetosTambem para programacao declarativa49

49Por que Scala?Compartilha muitas funcionalidades do JavaFX Script que fazem a programacao de interfaces mais facil:Checagem estatica de tipos Encontre seus erros em tempo de compilacaoClosures Misture os comportamentos e passe-os como referenciaDeclarativa Expresse a interface como ela deve aparecer

Scala tambem suporta Type Safe DSLs!Conversoes implicitas extensao de classes typesafeOverloading de operadores com regras de precedenciaDelayedInit / @specialized funcionalides avancadas da linguagem5050Java vs. Scala DSLpublic class HelloStage extends Application {

public void start(Stage stage) { stage.setTitle("Hello Stage"); stage.setWidth(600); stage.setHeight(450); Scene scene = new Scene(); scene.setFill(Color.LIGHTGREEN); Rectangle rect = new Rectangle(); rect.setX(25); rect.setY(40); rect.setWidth(100); rect.setHeight(50); rect.setFill(Color.RED); scene.setRoot(new Group(rect)); stage.setScene(scene); stage.show(); }

public static void main(String[] args) { launch(HelloStage.class, args); }}object HelloJavaFX extends JFXApp { stage = new Stage { title = "Hello Stage" width = 600 height = 450 scene = new Scene { fill = LIGHTGREEN content = Seq(new Rectangle { x = 25 y = 40 width = 100 height = 50 fill = RED }) } }}5121 Linhas430 Caracteres17 Linhas177 CaracteresStage.add??51object DisappearingCircles extends JFXApp { stage = new Stage { title = "Disappearing Circles" width = 800 height = 600 scene = new Scene { fill = BLACK content = for (i 0}).play()}64Sobre o projeto Visage65Metas do projeto Visage:Compila para JavaFX Java APIsEnvolve toda a linguagem (Annotations, Maps, etc.)Suporta outros Toolkits

Venha participar do time!Para mais informacoes: http://visage-lang.org/Visage e uma domain specific language (DSL) projetada para suportar a funcao de construcao de interfaces.

E sobre o JavaFX no VisageStage { title: "Hello Stage" width: 600 height: 450 scene: Scene { fill: Color.LIGHTGREEN content: Rectangle { x: 25 y: 40 width: 100 height: 50 fill: Color.RED } }}66E sobre o JavaFX no VisageStage { title: "Hello Stage" width: 600 height: 450 scene: Scene { fill: Color.LIGHTGREEN content: Rectangle { x: 25 y: 40 width: 100 height: 50 fill: Color.RED } }}67E sobre o JavaFX no VisageStage { title: "Hello Stage" width: 600 height: 450 Scene { fill: Color.LIGHTGREEN Rectangle { x: 25 y: 40 width: 100 height: 50 fill: Color.RED } }}68Visage e um JavaFX Script++Parametros padraoNova sintaxe para:Angulos 35deg, 4rad, 1turnCores #DDCCBB, #AA33AA|CCMedidas 5px, 2pt, 3in, 4spChecagem de null-referencevar width = rect!.widthBindable Maps embutida (Em breve!)var fruitMap = ["red" : apple, "yellow" : banana]var fruit = bind fruitMap["red"]69Visage e JavaFX 2.0 foram feitos um para o outroBinding melhoradoRetem a avaliacao tardia de variaveis com um poder expressivo adicionalColecoes integradasSequencias e mapas automaticamente convertidos entre JavaFX Observable Lists/MapsSintaxe de animacoes embutidaColoca o JavaFX em um subsistema de animacoesProve uma API mais limpa e consistente70ConclusaoVoce pode escrever aplicacoes JavaFX com Java puroJavaFX tambem e utilizavel por linguagens alternativasVoce pode ter o suporte melhorado utilizando bibliotecas DSLGroovyFXScalaFXOu uma linguagem de interfaces que roda na JVMVisage71Pro JavaFX 2 Platform em breve!Primeiro trimestre de 2012Todos os exemplos reescritos em JavaCobre as novas bibliotecas da versao 2.0Incluira ScalaFX, GroovyFX e Visage72

73Stephen [email protected]: @steveonjava73