JavaFX Demo学习1-----Clock
第一个附件是使用JavaFX编写一个Clock的教程,很详细。运行结果如下。
学习一门语言最好的方法就是看例子+多动手。所以先从它的Demo开始学习。这个Demo还是比较简单的。总共就一百多行。但是效果却不凡
从Frame开始看吧!但码如下:
Frame { title:"JavaFX 时钟应用程序" width:295 height: 325 closeAction:function() { java.lang.System.exit( 0 ); } visible:true stage:Stage { content: Clock{} } }
public abstract class CustomNode extends Node {
/** * Define your own node classes by extending this class and * implementing its create method. Example: @exampleimport javafx.scene.*;import javafx.scene.paint.*;import javafx.scene.geometry.*;public class Bars extends CustomNode { public function create():Node { return Group { content: for(x in [0..4]) { Rectangle { y: indexof x * 20 width: 100 height: 10 fill:Color.RED } } } }}Bars { }@endexample
public class Clock extends CustomNode { public attribute radius:Number = 77 ; public attribute centerX:Number = 144 ; public attribute centerY:Number = 144 ; public attribute hours:Number; public attribute minutes:Number; public attribute seconds:Number; public function nextTick () { var now = new Date(); seconds = now.getSeconds(); minutes = now.getMinutes(); hours = now.getHours(); } public function create(): Node { return Group { content:[ ImageView { image: Image { url: "{__DIR__}clock_background.png" } }, Group{ transform: Translate { x: centerX, y: centerY } content: [ Circle { radius: radius + 10 //stroke: Color.BLUE }, // code to display the numbers for every third hour for (i in [3, 6, 9, 12]) Text { transform:Translate { x :-5, y : 5 } font:Font {size:16 style:FontStyle.BOLD } x:radius * (( i + 0 ) mod 2 * ( 2 - i / 3)) y:radius * (( i + 1 ) mod 2 * ( 3 - i / 3)) content:"{i}" },//code to display a circle for the rest of the hours on the clock for (i in [1..12]) if (i mod 3 != 0 ) then Circle { transform:Rotate { angle:30 * i } centerX:radius radius: 3 fill:Color.BLACK } else[ ],// code for the clock's first center circle Circle { radius:5 fill:Color.DARKRED },//code for the smaller center circle Circle { radius:3 fill:Color.DARKRED },//code for the seconds hand Line { transform:Rotate { angle: bind seconds * 6 } endY:-radius - 3 strokeWidth: 2 stroke:Color.RED },//code for the hour hand Path { transform:Rotate { angle:bind (hours + minutes / 60) * 30 - 90 } fill:Color.BLACK elements: [ MoveTo {x:4, y: 4}, ArcTo {x:4 y:-4 radiusX:1 radiusY: 1}, LineTo{ x:radius - 15 y: 0}, ] },// code for the minutes hand Path { transform:Rotate { angle: bind minutes * 6 - 90} fill:Color.BLACK elements: [ MoveTo {x:4, y: 4}, ArcTo {x:4 y:-4 radiusX:1 radiusY: 1}, LineTo{ x:radius y: 0},] } ] }] }; } init{ var timeline = Timeline { repeatCount: Timeline.INDEFINITE keyFrames : [ KeyFrame { time : 1s action: function() { nextTick(); } } ] } timeline.start(); }}
ImageView { image: Image { url: "{__DIR__}clock_background.png" } }