Strict Standards: Declaration of Walker_Page::start_el() should be compatible with Walker::start_el(&$output) in /home/citiz68/public_html/javafxblogs/wp-includes/classes.php on line 596

Strict Standards: Declaration of Walker_Page::end_el() should be compatible with Walker::end_el(&$output) in /home/citiz68/public_html/javafxblogs/wp-includes/classes.php on line 596

Strict Standards: Declaration of Walker_PageDropdown::start_el() should be compatible with Walker::start_el(&$output) in /home/citiz68/public_html/javafxblogs/wp-includes/classes.php on line 613

Strict Standards: Declaration of Walker_Category::start_lvl() should be compatible with Walker::start_lvl(&$output) in /home/citiz68/public_html/javafxblogs/wp-includes/classes.php on line 707

Strict Standards: Declaration of Walker_Category::end_lvl() should be compatible with Walker::end_lvl(&$output) in /home/citiz68/public_html/javafxblogs/wp-includes/classes.php on line 707

Strict Standards: Declaration of Walker_Category::start_el() should be compatible with Walker::start_el(&$output) in /home/citiz68/public_html/javafxblogs/wp-includes/classes.php on line 707

Strict Standards: Declaration of Walker_Category::end_el() should be compatible with Walker::end_el(&$output) in /home/citiz68/public_html/javafxblogs/wp-includes/classes.php on line 707

Strict Standards: Declaration of Walker_CategoryDropdown::start_el() should be compatible with Walker::start_el(&$output) in /home/citiz68/public_html/javafxblogs/wp-includes/classes.php on line 730
JavaFX : JavaFX编程

JavaFX常用技巧( How-Tos )

分类: JAVAFX技术, JavaFX技巧, JavaFX编程.
标签: ,

Javafx.com中发布了一组实用的编程技巧例子,非常有参考意义。内容从最基础的概念到示范程序都有,另外还按照常见的API调用分类说明,对入门、初级和中级JavaFX学习者都是很好的借鉴。

链接如下:


JavaFX How-Tos (英文)

比较重要或者有意思的内容有:

1)绑定(binding)

2)基础UI(Basic UI)

3)视觉效果(Visual Appeal)

4) 近阶内容(transition切换等)

5)JavaFX和Java,Javascript,SWING交互



本人的Pac-Man和WishTree程序被收录在Game应用程序范例里面,实在感到荣幸。




Other links:


iPhone App Canada Citizen Test
Canadian Citizenship Test for iPhone
Canadian Citizen Exam
iPhone App iCitizenship Canada

评论 (0) 2009年11月14日

JavaFX多用户在线应用实例:许愿树联机版

分类: JavaFX编程, 许愿树.
标签: ,

JavaFX作为RIA(Rich Internet Application)的开发语言,主要的特点在’R'和’I'两点上,即丰富的客户端和联网的应用。最近我把原来用JavaFX1.1写的许愿树程序改成了联机版,成为了一个3层架构应用,如下图所示,展现层是JavaFX实现的富客户端,中间层是Web Server和PHP,数据库层是MySQL。

这个新的许愿树程序可以让不同的人在许愿树上悬挂自己的愿望星,所有人看到的是同一棵树。你可以点击下图来试试这个最新联网版的许愿树啦,注意要输入email地址,以便以后修改愿望,每个人请最多留一个星星:

在JavaFX客户端的GUI部分,代码基本上和单机版的一样,已经在前面几篇文章中介绍了(参见文末的链接)。在和server通信的过程中采用了JavaFX 1.2的HttpRequest类来实现。Server的数据采用了JSON的格式(一种基于JavaScript的对象表达方式),在客户端可用javafx提供的PullParser类来解析。

首先,我们来看看客户端启动后首次加载数据的代码。在Main.fx中,我们有如下部分的代码:

var parser = PullParser {
    documentType: PullParser.JSON;

    onEvent: function(event: Event) {
      var content: String;
      var name: String;
      var id: String;
      var email: String;
      var color: Integer;
      var time: String;
      var location: String;

      // parse the JSON data and populate object
      if(event.type == PullParser.END_VALUE) {

        if(event.name == "name") {
          star.name = event.text;
        }
        else if ( event.name == "content" ){
          star.wish = event.text;
        }
        else if ( event.name == "id" ){
          star.id = event.text;
         }
        else if ( event.name == "color" ){
          star.whichColor = event.integerValue;
        }
        else if ( event.name == "time" ){
          star.time = event.text;
        }
        else if ( event.name == "location" ) {
          var pos = event.text.indexOf( "_" );
          var x = event.text.substring(0,pos);
          var y = event.text.substring( pos+1 );

          star.translateX = Float.parseFloat(x);
          star.translateY = Float.parseFloat(y);
        }
        else if ( event.name == "Star" ){
          star.changeStatus();
          star.onMousePressed = handleClick;

          insert star after stage.scene.content[currentIndex++];
          star = Star {};
        }

      }
    }
  }

  function getAllStar() {
    request = HttpRequest {
      method: HttpRequest.GET
      location: ServerConnector.serverURL1
      onInput: function(is: InputStream) {
        try {
          parser.input = is;
          parser.parse();
        } finally {
            is.close();
          }
      }
    }

    request.start();
 }

我们创建了一个PullParser的实例,用来分析JSON格式的数据(见后),然后在函数getAllStar()中,HttpRequest实例采用了GET的放式从服务器端获取幸运星的数据,代码很简单,只需要在onInput中把输入流传给parser即可。从Web服务器上传回的JSON数据格式如下,其中id是Server端数据库中唯一的标识,location是星星在窗口中的位置,color是星星的颜色编码,其它属性都比较一目了然:

{
 "Star": {
   "name" : "John Smith",
   "content" : "This is a wish",
   "id" : "2",
   "location" : "300.0_240.0",
   "time": "2009-08-21 17:38:37",
   "color": 3
 },
 "Star": {
   "name" : "Homer Simpson",
   "content" : "This is another wish",
   "id" : "3",
   "location" : "288.0_238.0",
   "time": "2009-07-18 18:38:28",
   "color": 4
 }
}

当客户端从Server数据库中获得了这些星星的数据之后,就可以把之前保存的星星和愿望在树上显示出来了。在用户增加一颗星星之后,客户端会把愿望的数据传到服务器保存起来,采用的是HTTP的POST方式,把相关数据发送出去。代码如下,

/*
 * ServerConnector.fx
 */
package wishtree;

import java.net.URLEncoder;
import wishtree.Star;
import java.io.*;
import javafx.io.http.*;

/**
 * @author Henry Zhang   http://www.javafxblogs.com
 */

var baseURL = "http://localhost:8888/wishtree/";

public var serverURL1 = "{baseURL}getallstar.php";
var serverURL2 = "{baseURL}savestar.php";

public class ServerConnector extends HttpRequest {

  var star : Star = null;
  var paramString : String ;

  override var onOutput = function( os: java.io.OutputStream): Void {
        try {
            os.write(paramString.getBytes());
        } finally {
            os.close();
        }
    };

  override var onInput = function(is: java.io.InputStream) {
     try {
           var br = new BufferedReader( new InputStreamReader( is ) );
           var line: String;

           while ( ( line=br.readLine() ) != null )
           {
             if ( (star != null) and (star.id == "")  )
                star.id = line;
            }
        } finally {
            is.close();
        }
  };

public function saveStar( s: Star ) {
  if ( s.id.length() == 0 )
    star = s;

  paramString = encode("name", s.name);
  paramString += "&{encode("id", s.id)}&" ;
  paramString += encode("location", "{s.translateX}_{s.translateY}" );
  paramString += "&{encode("content", s.wish )}";
  paramString += "&{encode("email", s.email)}" ;
  paramString += "&{encode("time", s.time)}&" ;
  paramString += encode("color", "{s.whichColor}" );

  headers = [
        HttpHeader {
            name: HttpHeader.CONTENT_LENGTH;
            value: "{paramString.getBytes().length}";
        }
       ];

  method = POST;
  location = serverURL2;
  start();
 }
}

function encode( k: String, v:String): String {
    var result = URLEncoder.encode( k, "UTF-8");
    var value = URLEncoder.encode( v, "UTF-8");
    result += "={value}"
}

服务器端的php代码比较简单,这里就不一一介绍了,有兴趣的可以下载代码看看,注意README.txt的说明。如果有什么问题,请留言。

相关文章:

JavaFX技巧:Java调用JavaFX例子

在JavaFX中的菜单

Swing应用中使用JavaFX的功能

用纯Java代码调用JavaFX的功能

JavaFX Multi-User Game Demo

其它:

NASCAR Diecast Car and Drivers Collectibles

NASCAR Driver Tony Stewart Diecast Car

NASCAR Diecast Car Jimmie Johnson NASCAR Diecast Car Dale Earnhardt

New US Citizenship Test Questions

Best Online US Citizenship Practice Test

US Citizenship Application Forms

评论 (0) 2009年08月18日

用纯Java代码调用JavaFX的功能

分类: JavaFX技巧, JavaFX编程.
标签: , , , ,

在JavaFX 1.0发布之后,本人撰写的文章JavaFX和Java之间的互操作性被各网站转载。文中总结了3种从Java调用JavaFX的方法。这三种方法分别为:

1. 用ScriptEngineManager类。这是基于JSR-223规范的java脚本API( scripting API)。可以在java程序中运行一些脚本,如 JavaFX script, javascript等。
2. 通过JavaFX reflection API。这是JavaFX提供的反射API,几乎可以调用所有的JavaFX类。
3. 先用JavaFX类实现一个Java的interface,然后Java程序可以通过这个interface来调用JavaFX的功能。这中间的interface起了个桥梁的作用。

第三种方法应该是比较“正规”而且“优美”的调用方式。但是也有一点不足:程序代码的入口必须从JavaFX启动。这是因为JavaFX程序比较容易生成JavaFX类的实例,从而可以供Java方使用。可是我们有时会碰到一些特定的情况,需要从Java端启动代码。例如,如果你已经有了一个较完整的Java程序,你需要用调用JavaFX的某些功能,这时候较好的方法是把Java作为程序的入口。为了解决这个问题,我把第2和第3种方法作了融合,大家可以看看下面的例子。

假定我们需要从Java中调用JavaFX的图表(charting)功能。我们首先用JavaFX reflection API生成JavaFX类的实例。然后我们再通过java的interface来使用它。因此,我们先定义一个Java的interface:

/*
 * JavaInterface.java
 *
 * @author Henry Zhang      http://www.javafxblogs.com
 */
package javatest;
public interface JavaInterface {
  public void addData(String name, float data);
  public void showChart();
}

下一步是创建JavaFX类MyChart来实现这个interface:

/*
 * MyChart.fx
 *
 * @author Henry Zhang     http://www.javafxblogs.com
 */
package javatest;

import javafx.scene.chart.PieChart;
import javafx.scene.Scene;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.scene.chart.PieChart3D;

public class MyChart extends JavaInterface {
  var chartData :  PieChart.Data[] = [];

  public override function addData( l:String, v: Number):Void {
    var labelString = l;

    var data =  PieChart.Data {
      label : l
      value : v
      action: function() {
        println("{labelString} clicked!");
      }
     } ;

    insert data into chartData;
  }

  public override function showChart() : Void {
    var chart =
      PieChart3D {
        data : chartData
        pieThickness: 25
        pieLabelFont: Font{ size: 9 };
        pieToLabelLineOneLength: 10
        pieToLabelLineTwoLength : 20
        pieLabelVisible: true
        pieValueVisible: true
        translateY: -50
     };

    Stage {
      title: "PieChart Window"
      width: 520
      height: 300
      scene: Scene {
        content: [
          Text {
            font : Font {
                    size : 16
                   }
            x: 200
            y: 20
            content: "Pie Chart"
          },
          chart
        ]
      }
    }
  }
}

最后就是从java类JavaTest中调用图表功能:

/*
 * JavaTest.java
 * @author Henry Zhang    http://www.javafxblogs.com
 */
package javatest;

import javafx.reflect.FXClassType;
import javafx.reflect.FXLocal;
import javafx.reflect.FXLocal.Context;
import javafx.reflect.FXLocal.ObjectValue;

public class JavaTest {
  public static void main(String args[]) {
    Context context = FXLocal.getContext();
    FXClassType instance = context.findClass("javatest.MyChart");
    ObjectValue obj = (ObjectValue)instance.newInstance();

    JavaInterface ji = (JavaInterface)obj.asObject();

    String [] labels = {"January", "Febuary", "March", "April"};
    int [] values = { 18, 20, 25, 37 };

    for ( int i=0; i < values.length; i++ ) {
      ji.addData(labels[i], values[i]);
    }

    ji.showChart();
  }
}

在代码中,这3句是创建JavaFX类javatest.MyChart实例,

    Context context = FXLocal.getContext();
    FXClassType instance = context.findClass("javatest.MyChart");
    ObjectValue obj = (ObjectValue)instance.newInstance();

而一下这句则是把JavaFX实例转化为Java可用的对象:

    JavaInterface ji = (JavaInterface)obj.asObject();

如果你用的是NetBeans IDE, 你可以在项目属性中把javatest.JavaTest类设为主类(Main class)(即启动类)。编译之后会生成一个javatest.jar文件。程序运行的结果如图:

Java PieChart via JavaFX

在命令行中可以采用以下方式:

   javafx -jar javatest.jar

实际上,可以用纯Java的方式来启动程序,只要把JavaFX的运行环境带上即可,如:

 java -Djava.library.path="<path to javafx sdk lib>"
     -classpath "<all javafx sdk jars>" -jar javatest.jar

因为JavaFX需要的jar文件很多,因此这种“最纯”的java方法使用起来比较麻烦。我觉得还是用javafx命令简洁些, 而且javafx就是上述java命令的封装而已。

如果有问题,请留言讨论。

本文的英文译文同步发表于:Calling JavaFX Classes from Pure Java Code.

评论 (1) 2009年06月21日

JavaFX吃豆人游戏的编写过程之四

分类: JavaFX编程, 吃豆人游戏.

JavaFX吃豆人游戏的第五篇文章上周已经发表。在最后的这篇文章中,详细介绍了精灵追逐吃豆人的算法。这可能是该游戏代码中最有趣的部分了。


在游戏编写时,通常需要考虑一些要素,如算法的效率、随机性、简洁度等。在文章中对这些问题都作了讨论。 在追逐算法中,程序采用了比较简单的距离优先的逼近算法。如下图所示:


图中的红色精灵从右到左移动,当它在交叉路口时,它可以选择向上或者向左移动。如果我们把它和吃豆人之间的X/Y方向上的距离和作为一个评估指标的话,我们可以得到这样一个结论: 向左走的距离为14,向上走距离缩短为12。因此向上可以使得红精灵更加逼近吃豆人。通过计算,我们就可以知道向上是个比较好的选择。如果吃豆人吞下魔法豆,我们只需要把积分方式取负运算,就可以立刻成为一个精灵的逃离算法。网上还有许多关于算法的介绍,但作为例子,本文中仅介绍一个最简单和最易实现的算法。全文可以参考这里。点击下图可以启动完整的吃豆人游戏:(JDK 1.5以上)


启动游戏

启动游戏


相关文章:

JavaFX应用实例、例子
用JavaFX编写的游戏Pac-Man
JavaFX实例探索教程
JavaFX特性和编程实例代码
JavaFX 1.2 程序迁移指南

快速升级到JavaFX SDK 1.2的方法
JavaFX吃豆人游戏的编写过程之二
JavaFX游戏吃豆人的编写过程


英文文章连载:


2009年5月14日 - 2009年6月11日:
Writing the Pac-Man Game in JavaFX


评论 (0) 2009年06月18日

JavaFX 1.2 程序迁移指南

分类: JAVAFX技术, JavaFX编程.
标签: , , ,

javafxblogs.com Rss_google Rss_zhuaxia Rss_xianguo


本文系经原作者Stephen Chin授权翻译,英文原文:The Definitive 1.2 Migration Guide,为方便起见,英文原文的副本也可参见本站转载。有关代码迁移和JavaFX 1.2新特性内容,还可以参考JavaFX网站的文章,或者本站文章JavaFX 1.2的新特性。以下译文中的红字部分为译者加注。



本文包含了从JavaFX 1.1迁移程序到JavaFX1.2最常见的变化,例如如语言本身、功能以及API的改变。如果你发现本文没有提到的变化,请在评论中留言。


基本原则

1) JavaFX 1.2 的二进制不兼容性:对于原来的jar文件或者其它第三方的JavaFX库,如JFXtras,必须经过重新编译才能在和JavaFX 1.2的代码兼容,否则会有编译错误。JFXtras将发布基于JavaFX 1.2的更新,新的版本就快就绪了。

2)内部的API将不能用了,如果你的代码包含了impl_或者sun.com的包,你的代码肯定需要修改。

3) 支持Linux和Solaris, 这是应该说是个新功能,这样你可以对用户自豪的宣称支持Linux。译者注:这里的Solaris应指OpenSolaris。


语言上的变化 JavaFX教程、实例、Demo

1)嵌套的块语句中不可以再有变量屏蔽(Shadowing)。原来可以有同名的变量分别处于内层和外层的块语句中,在内层的语句中的变量可以覆盖外层的同名变量。在JavaFX 1.2种,需要修改变量的名字来避免重名。

2)用mixin代替多类继承性。JAVAFX不再支持多类继承性,但是你可以继承一个类和多个mixin类。Mixin就像java中的interface,不同的是它可以有变量和已实现的方法,使得所有子类都可以使用。这点需要的修改也不多,只需要把原来多继承的类加上mixin关键字即可,如:

public mixin class Resizable { /* variables and functions here */ }

译者注:mixin也可以理解成可以多继承的抽象类(abstract class)

3) 在Sequence中,需要用逗号来分隔元素(除了那些用花括号结束元素)。这有点不方便,但实际上是件好事,因为可以避免以前很难追查的语言陷阱。JavaFX 1.2的新特性


Node类的变化 JavaFX编程实例

1)Node.boundsInScene 属性没有了,主要是性能方面的原因,好在有个容易替换且功能相同的调用:

node.localToScene(node.boundsInLocal)


2) Node.focusable 变为 Node.focusTraversable,虽是很小的API变化,但你应知道这点以免碰上编译错误。这是有关focus功能修正的一部分:当某个Node可见(visible)、可聚焦遍历(focusTravserable)并且没被禁用时,可以得到聚焦。(key listener将不再需要)

3) CustomNode.create() 将在 init 块之前调用,原来的方式是create()方法调用在init之后,在postinit之前。既然现在的调用在init之前,那么需要注意的是变量初始化的顺序,可能需要调整一些代码。

4) SwingControl.enabled -> Node.disable 这是一个在Node类中新的标志,统一地控制启用和禁用(enable/disable)。与之矛盾的SwingControl.enabled变量已经去掉了。

5) Rectangle2D -> Bounds 所有Rectangle2D的引用已经改为javafx.geometry.Bounds类了,在代码中可能会产生连锁反应。升级到JavaFX 1.2的简便方法


Layout类的变化 JavaFX Demo Game

1) min/max/pref -> getters 所有Resizable类的属性 (minimumWidth, minimumHeight, maximumWidth, maximumHeight, preferredWidth, preferredHeight) 已被替换为getter函数(getMinWidth, getMinHeight, getMaxWidth, getMaxHeight, getPrefWidth, getPrefHeight respectively)。其中 prefWidth/Height 函数可以代一个额外的参数,即在另一维度的空间大小。在高/宽有约束的layout中,如Flows,会非常有用,但也可以用-1来忽略该参数。

2) impl_layoutX/Y -> layoutX/Y 方法impl_layoutX和impl_layoutY正式替换为layoutX和layoutY变量。建议你使用这组变量来移动node到某个位置,这比translateX/Y要好。

3) impl_requestLayout() -> requestLayout()。 requestLayout 函数类似地从内部转为公开的API.

4) impl_layout -> doLayout()。 原来是用函数类设置layout,现在改为覆盖Parent.doLayout().

5) 增加了Panel类的声明式Layout。如果你在寻找功能上替代Container的方法,可以看看新的Panel类,它可以声明式设置layout,而且,它还能够通过变量覆盖min/max/pref缺省值,从而不用产生Container的子类.

6) Container中的新函数帮助实现布局(layout)。Container类里面有很多新函数,使得很容易来使用新的布局系统。切记要先完全读一遍,因为这样可以使你节约时间,同时可以遵循布局的最佳实践。

7) 不同的变换(transformation)顺序。过去transforms[]变量可让你在layoutBounds中使用变换,而scaleX/translateX/rotate等可以作用在布局之后. 现在transforms[]和transformation变量都统一在布局之后进行计算。


Skin/Control的变化: JavaFX技术应用编程交流

1) Skin.scene -> Skin.node。这个属性名称的变化可以减少易混淆的Scene类所带来的困惑。

2)去掉了Skin.computeXXX的方法。曾经有过一系列的computePreferredWidth/Height等方法,现在可直接用getPrefWidth/Height等函数,参见上文提到的Resizable类。


3)Skin成为抽象类。需要你实现contains和intersects方法。你可以使用新的JFXtras中的AbstractSkin类,或使用以下样板代码:

override function contains(localX:Number, localY:Number):Boolean {
    return node.contains(localX, localY);
}   

override function intersects(localX:Number, localY:Number,
      localWidth:Number, localHeight:Number):Boolean {
    return node.intersects(localX, localY, localWidth, localHeight);
}


4)新的行为(Behavior)类。这个类可以和Control及Skin一起使用来提供可重用的行为。

5)TextBox.text -> rawText, TextBox.value -> text。TextBox类现在重新调整了,text变为rawText,意义不变.


异步处理的变化: JavaFX Guy的博客
1) RemoteTextDocument类没有了。直接用HttpRequest类替代. 译者注:对于原来和后台Server交互的程序要小心这个变化,代码需要调整。

2) AbstractAsyncOperation类没有了。用新的任务基础设施来替代后台Java线程的通信。


动画(Animation)的变化: JavaFX教程、例子、编程论坛

1) Transition.interpolate -> Transition.interpolator。属性名称的改变,使得interpolate标志具有新的含义:可以成为是否做插值运算的开关。

2)Transition现在是继承Timeline类。这是个受欢迎的修改,使得Transitions很容易与Timelines一起使用。因为这个变化,ParallelTransition和SequentialTransition类现在可以有一个sequence保存的Timeline实例。 译者注:这个变化比较有意义,因为原来的Transition也可以作为动画的一种机制,容易令人糊涂。

译者注:以下两点从javafx.com中摘录翻译。

3)KeyFrame中不再提供timelines变量,但是可以用ParallelTransition和SequentialTransition这两个类来实现同样的功能。

4)Transition类中的timelineDirty变量由markDirty()方法替代。


和Java相同的函数: JavaFX Discussion Blog

1)java.lang.Math -> javafx.util.Math。新的JavaFX数学函数库, 使用JavaFX数学库的好处是可以在移动设备上应用(包括pow, log, 等)。

2)java.lang.Properties -> javafx.util.Properties。和Java相似的又一个类,但是可以移植到移动设备上。但需要注意的是,JavaFX的属性文件和Java属性文件格式不一致。


CSS支持的变化:

1)CSS 更新的缺陷(RT-4817)。样式(Stylesheet)的更新不再影响新增的Nodes。同时,你可以强制stylesheet的更新,方法如下:

def senators = bind model.senators on replace {
    delete sceneRef.stylesheets;
    sceneRef.stylesheets = "{__DIR__}styles.css";
}


2) CheckBoxSkin.textFill 不接受样式(RT-4819)。选项标志本身可以使用你所设置的样式(style),但是文本却不行。现在变通的做法是创建没有文本的checkbox,然后在旁边加上一个具有样式和事件处理机制的文本接点(text node)。

3) 不能从CSS中更新control中的skin属性 (RT-4820) 。这曾经是另一个skin支持上的bug。现在可以在代码中实现了。


Production Suite: 作者Henry Zhang的JavaFX技术博客

1) UiStub -> FXDNode。UiStub类现用FXDNode替代了, 增加了更多的功能,包括后台加载(backgroundLoading)和临时替代图像(placeholder images)。 译者注:以下代码示例来自javafx.com:

Scene {
  content: FXDNode {
     url: "{__DIR__}mygraphics.fxz"
     backgroundLoading: true
     placeholder: Text { x: 10 y: 10 content: "Loading graphics ..."}
   }
}


其它:
1) Image.fromBufferedImage()取消了。功能移至SwingUtils.toFXImage()。要记住的是,使用这个函数会在移植代码到移动设备时受到限制。

2) Color.fromAWTColor()取消了。这又是一个AWT痕迹的销除。JavaFX的Color类应该是非常完善的了,所以没有什么理由我们还要继续使用AWT的色彩体系。

3) Duration.toDate没有了。据我所知,应该没有相应的函数,但是我们总是可以获取duration的整数值然后直接操作它。

4) Affine类中不同的变量名称。如果你用到了Affine类, 你的代码很可能需要修改了,因为变量名称换成了更有说明性的方法名,但是功能还是一样的。


评论 (0) 2009年06月14日

JavaFX 1.2 迁移指南(英文)

分类: JAVAFX技术, JavaFX编程.
标签: , , ,

本文经授权转载自Stephen Chin的英文文章The Definitive 1.2 Migration Guide中文翻译参见这里

Below is the JavaFX 1.2 migration guide written by Stephen Chin. The original article can be found on his blog steveonjava.com. I post his article here for readers who cannot visit Stephen’s blog due to networking problem. Steve, thanks a lot for allowing me to share it here. The Chinese translation can be found here.

The Definitive 1.2 Migration Guide

by Stephen Chin


If you have made it this far, you are a serious JavaFX hacker!  This section covers the most common language, functionality, and API changes that you will encounter when migrating applications from JavaFX 1.1.  If you notice anything that is not covered, feel free to add it in the comments and I will update the guide as appropriate.


General:

  • JavaFX 1.2 is not binary compatible – If you use any jars or third-party JavaFX libraries (such as JFXtras), they must be recompiled for the new release or you will get compilation errors.  Speaking of JFXtras, a new version which has been updated for JavaFX 1.2 is nearly ready, and will be announced here when it is complete!
  • All internal-only APIs are broken – More details broken out by section below, but if you rely on any impl_ or com.sun packages, your code will definitely need to be updated.
  • Linux and Solaris are now supported – This is more of a feature than a migration issue, but if you have users on multiple platforms you can now proudly state that Linux is supported.


Language Changes:

  • No more variable shadowing in nested blocks – It previously was valid to name a variable the same in both the inner and outer block of an expression.  The variable in the inner block would simply replace the one in the outer.  However, this will throw a compiler error in JavaFX 1.2.  The fix is simple…  just use a different variable name.
  • Use Mixins instead of Multiple Inheritance – JavaFX no longer supports multiple inheritance.  Instead you can extend one class and as many mixins as you like.  Mixins are like interfaces in Java, except they can have variables and implementations that are shared by all the classes that extend them.  The only change you have to make in your application to start using mixins is to add the mixin keyword when you define a new class like this:
public mixin class Resizable { /* variables and functions here */ }
  • Commas are required in sequences – Sequences now require commas between elements (except those that end in braces).  This is a little less convenient, but actually a very good thing, because it avoids several language pitfalls that were hard to track down before.


Node Changes:

  • Node.boundsInScene is gone – This was removed for performance reasons, fortunately there is an easy replacement that offers the same functionality:
node.localToScene(node.boundsInLocal)
  • Node.focusable -> Node.focusTraversable – Small API change, but good to know when you get the compilation error on focusable not found.  This is part of a larger focus fix where any Node that is visible, focusTraversable, and not disabled will be eligible for focus (a key listener is no longer required).
  • CustomNode.create() gets called before init – Previously the CustomNode create() method would get called after init and before postinit.  Now that it gets called even earlier than init, some of your code may not work correctly.  Make sure that any variables you are depending upon in the create() method are either initialized inline or have a bind declaration so they get updated once set.
  • SwingControl.enabled -> Node.disable – There is a new disable flag on the Node class that is used universally across all controls to enable or disable them.  This conflicted with the old SwingControl.enabled variable, which has now been removed.
  • Rectangle2D -> Bounds – All references to Rectangle2D have been changed to the new javafx.geometry.Bounds class, which may have a ripple effect through your code.


Layout Changes:


  • min/max/pref -> getters – All of the Resizable methods (minimumWidth, minimumHeight, maximumWidth, maximumHeight, preferredWidth, preferredHeight) have been replace with function getters (getMinWidth, getMinHeight, getMaxWidth, getMaxHeight, getPrefWidth, getPrefHeight respectively).  The prefWidth/Height functions take an extra parameter, which is the amount of space in the opposite dimension.  This is very useful for doing height or width constrained layouts, such as Flows, but can be ignored by passing -1.
  • impl_layoutX/Y -> layoutX/Y – The impl_layoutX and impl_layoutY methods have been replaced with official layoutX and layoutY variables.  It is recommended that you use these variables over translateX/Y if you are moving nodes into position.
  • impl_requestLayout() -> requestLayout() – The requestLayout function has similarly moved from an internal to a public API.
  • impl_layout -> doLayout() – Rather than having a function to set the layout on, you now override Parent.doLayout().
  • Panel class added for declarative layouts – If you are looking for a functional alternative to Container, take a look at the new Panel class, which lets you set the layout declaratively.  It also has variables to override the default min/max/pref values without subclassing Container.
  • New functions on Container to help with layouts – There are a whole slew of new functions on the Container class that make it easier to work with the new layout system.  Make sure to read through them, because they will both save you time and help you follow the best practices for layout design.
  • Different transformation order – Previously the transforms[] variable allowed you to apply transformations included in the layoutBounds, while scaleX/translateX/rotate etc. were applied after layout.  Now both transforms[] and the transformation variables are calculated after layout uniformly.


Skin/Control Changes:


  • Skin.scene -> Skin.node – The name of the Node on Skin has changed from scene to node, which helps reduce confusion with the Scene class.
  • Skin.compute* methods removed – There were a series of computePreferredWidth/Height/etc. methods that were removed.  Instead you can directly use the getPrefWidth/Height/etc. methods on the Resizable class mentioned above.
  • Skin is now abstract – The Skin class is now abstract, and required that you implement your own contains and intersects methods.  You can either do this by using the new JFXtras AbstractSkin class or using the following boilerplate code:
override function contains(localX:Number, localY:Number):Boolean {
    return node.contains(localX, localY);
}

override function intersects(localX:Number, localY:Number,
   localWidth:Number, localHeight:Number):Boolean {
    return node.intersects(localX, localY, localWidth, localHeight);
}
  • New Behavior class – There is a new Behavior class that is meant to be used together with Control and Skin to provide reusable behaviors.
  • TextBox.text -> rawText, TextBox.value -> text – There was some swizzling of variables on the TextBox class.  What used to be text changed to rawText, and value now has the same semantics text used to have.


Asynchronous Changes:


  • RemoteTextDocument has been removed – Use HttpRequest directly instead.
  • AbstractAsyncOperation has been removed – Use the new Task infrastructure instead for communcating with Java code running in a background thread.


Animation Changes:


  • Transition.interpolate -> Transition.interpolator – A small name change to make room for a new interpolate flag that allows you to turn on or off interpolation altogether.
  • Transition now extends Timeline - This is a welcome change, which makes it much easier to work with Transitions and Timelines together.  To support this change ParallelTransition and SequentialTransition now take a sequence of Timeliens.


Java Equivalent Functions:

  • java.lang.Math -> javafx.util.Math – There is a new JavaFX math library, which is a drop-in replacement for the Java math library.  The main advantage of using the new JavaFX math library is that all functions are supported on mobile devices (including pow, log, etc.).
  • java.lang.Properties -> javafx.util.Properties – Another class that is similar in functionality to the Java equivalent, but portable to mobile.  Be warned, however, that the JavaFX properties file format is not the same as the standard Java properties file format.


CSS Changes:

  • CSS Update Defect (RT-4817) – Stylesheet updates no longer affect newly added Nodes due to a known defect.  In the meantime, you can do this to force a stylesheet refresh:
def senators = bind model.senators on replace {
    delete sceneRef.stylesheets;
    sceneRef.stylesheets = "{__DIR__}styles.css";
}
  • CheckBoxSkin.textFill doesn’t accept styles (RT-4819) - The check mark will pick up the style you set, but the text won’t.  The workaround for now is to create a checkbox with empty text and add a text node beside it with the correct styling and event handlers.
  • Can’t update the skin property of Control from CSS (RT-4820) – Another bug in the skin support.  You can set this in code instead for now.


Production Suite:

  • UiStub -> FXDNode – UiStub has been replaced with FXDNode, which includes some extra functionality, such as backgroundLoading, and placeholder images.


Miscellaneous:

  • Image.fromBufferedImage() removed – This has moved to SwingUtils.toFXImage().  Remember that if you use this function it will limit portability to mobile devices.
  • Color.fromAWTColor() removed – Yet another AWT-ism that has been removed. The JavaFX Color class is pretty thorough, so there shouldn’t be any reason to work with AWT Colors.
  • Duration.toDate is gone – As far as I know there is no equivalent functionality, but you can always get a duration’s value as a long and manipulate it directly.
  • Different variable names for the Affine class – If you use the Affine class, then your code is likely to break due to the new, more descriptive, method names, but the functionality is the same.


Whew!  …that was quite a lot to take in.  If you are interested to read more about the JavaFX 1.2 release including the new controls, layouts, and other functionality, the best source is to checkout the Pro JavaFX book that Jim, Dean, Weiqi, and I are writing.  It is almost fully updated for the JavaFX 1.2 release, and is available in Alpha right now from the book website.


I want to give a special thanks to Richard Bair and Amy Fowler from the Sun JavaFX team for providing a lot of valuable information on the JavaFX 1.2 release along the way.

Happy hacking on JavaFX 1.2!

评论 (0) 2009年06月13日

JavaFX吃豆人游戏的编写过程之三

分类: JavaFX编程, 吃豆人游戏.
标签: ,

javafxblogs.com Rss_google Rss_zhuaxia Rss_xianguo

6月4日发表了英文连载中的第4篇文章。在这篇文章中,主要介绍了吃豆人和精灵之间互动的代码实现。代码可在“JavaFX游戏实例共享网站”中下载。


到上一篇文章为止,我们已经实现了游戏中所有的人物。现在我们来增加吃豆人和精灵追逐和互“吃”的处理逻辑。如果吃豆人和精灵相遇,只有两种情况,吃豆人吃掉精灵或者反之。如果吃豆人刚刚吞吃了魔法豆,他可以吃掉精灵,否则吃豆人就会损失一条命,这时,需要播放一段吃豆人消失的动画(如下图所示):
shriking pac-man


这个动画在DyingPacMan类中实现,代码如下:


public class DyingPacMan extends Arc {

   var timeline = Timeline {
      repeatCount: 1
      keyFrames: [
        KeyFrame {
           time: 600ms
           action: function() {
        // hide the pacMan character and ghosts before the animation
              maze.pacMan.visible = false;

              for ( g in maze.ghosts ) {
                 g.hide();
              }
              visible = true;
            }
           values: [ startAngle => 90, length=>360 ];
         },
        KeyFrame {
           time: 1800ms
           action: function() {
              visible = false;
            }
           values: [ startAngle => 270 tween Interpolator.LINEAR,
                     length => 0 tween Interpolator.LINEAR ]
         },
      ]
    }

 ... 代码省略 ...
}


在这个动画中,定义了2个KeyFrames,一个在600ms,另一个在1800ms。在这两个关键帧中采用了JavaFX的线性插值(Interpolator.LINEAR)方式。线性插值的作用就是把动画中数据按照时间关系,在帧与帧之间线性变化,从而实现平滑的动画效果。在上述代码中,两个实例变量:startAnglelength, 通过线性的均匀变化,实现了我们需要的动画过程。参考下图的时间轴。第一个关键帧的时间是600ms而不是0ms,是因为我们希望游戏在这瞬间稍微停顿600ms。
timeline pac-man


好啦,到目前为止,游戏已经基本完成了,可以玩了。唯一不足就是精灵现在还是随机移动的,游戏的难度不大。不要紧,我们将在下周的文章中详细讨论。现在就点击下图来试一下这个游戏吧:(JDK1.5以上, Java Web Start 自动启动)


click to run
click to run



相关文章:

JavaFX应用实例、例子
用JavaFX编写的游戏Pac-Man
JavaFX Guy的博客
JavaFX 1.2的新特性
怎样用JavaFX编写游戏:吃豆人(Pac-Man)

JavaFX吃豆人游戏的编写过程之二
JavaFX游戏吃豆人的编写过程


英文文章连载:


第一篇文章,2009年5月14日:
Writing the Pac-Man Game in JavaFX - Part 1

第二篇文章,2009年5月21日:
Writing the Pac-Man Game in JavaFX - Part 2

第三篇文章,2009年5月28日:
Writing the Pac-Man Game in JavaFX - Part 3

第四篇文章,2009年6月4日:
Writing the Pac-Man Game in JavaFX - Part 4

评论 (0) 2009年06月06日

JavaFX游戏吃豆人的编写过程

分类: JavaFX编程.
标签:

在JavaFX 1.0发布不久时,作为编程练习,我写了一个JavaFX游戏:Pac-Man,又称为PC MAN或“吃豆人”。Pac-Man是上世纪80-90年代非常著名的一款游戏,起源于日本,风靡全球。我写的JavaFX Pac-Man游戏引起了不少关注(参见文章:JavaFX 演示游戏:PAC-MAN http://www.javafxblogs.com/%e7%94%a8javafx%e7%bc%96%e5%86%99%e7%9a%84%e6%b8%b8%e6%88%8fpac-man/),很多读者询问如何用JavaFX编制这样的游戏,并且希望能得到原代码。

点击启动游戏

点击启动游戏

(点击画面可以启动JavaFX的Pac-Man游戏)

最近,我把编制该游戏的过程写成介绍文章,在O’Reilly出版社的insideRIA.com上连载。由于时间关系,文章暂时只有英文的,稍后会把它改写成中文的版本。感兴趣的读者可以先看看英文原文,下源代码看看。在文章中,有多处Java Web Start的链接,可以一边阅读一边看看程序是如何运行的。目前,连载的前2篇文章已经发表,以后每周四(中国时间周五)发表一篇。第一篇文章介绍了Java的数据模型,用基本JavaFX的Shape类来绘制迷宫以及豆子。第二篇文章介绍了如何实现Pac-Man的动画,如何用键盘控制人物来吃豆子的动作等。相关的JavaFX功能演示包括:

. shapes
. animation
. keyboard handling
. java code integration
. Transfromation

相关信息:

第一篇文章,2009年5月14日:
Writing the Pac-Man Game in JavaFX - Part 1

第二篇文章,2009年5月21日:
Writing the Pac-Man Game in JavaFX - Part 2

用JavaFX编写的游戏Pac-Man
如何编写JavaFX游戏:Pac-Man(吃豆人)

评论 (4) 2009年05月22日