JavaのGUIはSwingなどを利用して作成されてきました。このSwingによるGUI作成にはいろいろと問題がありました。まず、「非常に面倒である」という点。Swingは、正直、ちょっとしたものを作るには複雑すぎるのです。JavaFXは、非常にシンプルなスクリプト言語の形をしています。

Swingと同等レベルのGUIを構築できながら、しかも扱いは非常に単純です。また、JavaFXによるGUIの作成は、手続き方式ではなく「宣言」式に行うことができます。GUIを構造的に記述し作成できるのです。これは、非常に分かりやすいです。

では、JavaFXを使って簡単な「Hello World」サンプルを作ってみましょう。

1)、JavaのCanvas/Panelみたいなシーン(Scene)を追加する

  1. import javafx.stage.Stage;
  2. import javafx.scene.Scene;   // added Scene fucntionality
  3. import javafx.scene.paint.Color;   // added colors

2)、Stageを追加する

  1. Stage {
  2. title: “Hello World”    // Changed title to “Hello World”
  3. visible: true
  4. scene: Scene {
  5.         width: 250            // Scene width instead of  Stage width
  6.         height: 80             // Scene height instead of Stage
  7.         fill: Color.BLACK   // Color is Black
  8. }

3)、実行してみよう

HWScene

4)、全部黒だったら見た目は悪いですね。次は文字を表示用長方形を追加する

  1. import javafx.scene.shape.Rectangle// For drawing Rectangles

下記のソースも追加する

  1. scene: Scene {
  2. width: 250
  3. height: 80
  4. fill: Color.BLACK
  5. content: Rectangle {     // add an array of contents, here just one element
  6.     x: 10                          // x position for the rectangle
  7.     y: 10                          // y position for the rectangle
  8.     width: 230                 // width of rectangle starting at ‘x’
  9.     height: 60                 // height of rectangle starting at ‘y’
  10.     fill: Color.BLUE         // Fill rectangle with BLUE color
  11. }
  12. }

5)、もう一回動かしてみよう

HWRect

6)、最後は、表示文字ソースを追加する

  1. import javafx.scene.text.Text;
  2. import javafx.scene.text.Font;

下記のソースも追加する

  1. fill: Color.BLACK
  2. content: [                // Note that contents is now an array instead
  3.     Rectangle {        // this code remains the same as above except that the corners are round now
  4.         x: 10 y: 10
  5.         width: 230 height: 60
  6.         arcWidth: 20  arcHeight: 20
  7.         fill: Color.BLUE
  8.     }
  9.     Text {                  // This is the new code I added for adding text lables
  10.         x: 40 y: 50
  11.         font: Font { size: 20 }
  12.         fill: Color.WHITE
  13.         content: "Hello JavaFX World!"
  14.     }
  15. ]

7)、最終の結果:

HWButton

メインコンテンツEND ■
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Posted on Saturday, 15th November 2008 by admin

Tags: , , ,
Posted in Java | Comments (0) | 3,277 views

Leave a Reply