Javafx-event-handling

提供:Dev Guides
移動先:案内検索

JavaFX-イベント処理

JavaFXでは、GUIアプリケーション、Webアプリケーション、およびグラフィカルアプリケーションを開発できます。 このようなアプリケーションでは、ユーザーがアプリケーション(ノード)と対話するたびに、イベントが発生したと言われます。

たとえば、ボタンをクリックする、マウスを動かす、キーボードから文字を入力する、リストから項目を選択する、ページをスクロールするなどのイベントが発生します。

イベントの種類

イベントは大きく次の2つのカテゴリに分類することができます-

  • フォアグラウンドイベント-ユーザーの直接的な対話を必要とするイベント。 これらは、グラフィカルユーザーインターフェイスのグラフィカルコンポーネントと対話する人の結果として生成されます。 たとえば、ボタンをクリックする、マウスを動かす、キーボードから文字を入力する、リストから項目を選択する、ページをスクロールするなど
  • バックグラウンドイベント-エンドユーザーの相互作用を必要とするイベントは、バックグラウンドイベントとして知られています。 バックグラウンドイベントの例は、オペレーティングシステムの中断、ハードウェアまたはソフトウェアの障害、タイマーの期限切れ、操作の完了です。

JavaFXのイベント

JavaFXは、さまざまなイベントを処理するためのサポートを提供します。 パッケージ javafx.eventEvent というクラスは、イベントの基本クラスです。

そのサブクラスのインスタンスはイベントです。 JavaFXは、さまざまなイベントを提供します。 それらの一部を以下にリストします。

  • マウスイベント-これは、マウスがクリックされたときに発生する入力イベントです。 MouseEvent という名前のクラスで表されます。 これには、マウスクリック、マウス押下、マウスリリース、マウス移動、マウス入力ターゲット、マウス終了ターゲットなどのアクションが含まれます。
  • キーイベント-これは、ノードでキーストロークが発生したことを示す入力イベントです。 KeyEvent という名前のクラスで表されます。 このイベントには、キーの押下、キーのリリース、キーの入力などのアクションが含まれます。
  • ドラッグイベント-これは、マウスがドラッグされたときに発生する入力イベントです。 DragEvent という名前のクラスで表されます。 入力されたドラッグ、ドロップされたドラッグ、入力されたターゲットのドラッグ、終了したターゲットのドラッグ、上にドラッグなどのアクションが含まれます
  • ウィンドウイベント-これは、ウィンドウの表示/非表示アクションに関連するイベントです。 WindowEvent という名前のクラスで表されます。 ウィンドウの非表示、ウィンドウの表示、ウィンドウの非表示、ウィンドウの表示などのアクションが含まれます。

イベント処理

イベント処理は、イベントを制御し、イベントが発生した場合に何をすべきかを決定するメカニズムです。 このメカニズムには、イベントが発生したときに実行されるイベントハンドラーと呼ばれるコードがあります。

JavaFXは、イベントを処理するハンドラーとフィルターを提供します。 JavaFXでは、すべてのイベントに-

  • ターゲット-イベントが発生したノード。 ターゲットは、ウィンドウ、シーン、およびノー​​ドです。
  • ソース-イベントが生成されるソースは、イベントのソースになります。 上記のシナリオでは、マウスがイベントのソースです。
  • Type -発生したイベントのタイプ。マウスイベントの場合–マウスが押された状態、マウスが離された状態がイベントのタイプです。

次のようにグループオブジェクトを使用して、サークル、停止、再生ボタンが挿入されたアプリケーションがあると仮定します-

サンプルアプリケーション

再生ボタンをクリックすると、ソースはマウスになり、ターゲットノードは再生ボタンになり、生成されるイベントのタイプはマウスクリックになります。

JavaFXでのイベント処理のフェーズ

イベントが生成されるたびに、JavaFXは次のフェーズを経ます。

ルート建設

イベントが生成されるたびに、イベントのデフォルト/初期ルートは*イベントディスパッチチェーン*の構築によって決定されます。 ステージからソースノードへのパスです。

上記のシナリオで再生ボタンをクリックしたときに生成されるイベントのイベントディスパッチチェーンを次に示します。

再生ボタン

イベントキャプチャフェーズ

イベントディスパッチチェーンの構築後、アプリケーションのルートノードがイベントをディスパッチします。 このイベントは、ディスパッチチェーン内のすべてのノード(上から下)に移動します。 これらのノードのいずれかに、生成されたイベントに対して filter が登録されている場合、実行されます。 ディスパッチチェーン内のどのノードにも生成されたイベントのフィルターがない場合、ターゲットノードに渡され、最終的にターゲットノードがイベントを処理します。

イベントバブリングフェーズ

イベントバブリングフェーズでは、イベントはターゲットノードからステージノードに移動します(下から上)。 イベントディスパッチチェーン内のノードのいずれかに、生成されたイベント用に登録された handler がある場合、実行されます。 これらのノードにイベントを処理するハンドラがない場合、イベントはルートノードに到達し、最終的にプロセスが完了します。

イベントハンドラーとフィルター

イベントフィルターとハンドラーは、イベントを処理するアプリケーションロジックを含むものです。 ノードは、複数のハンドラー/フィルターに登録できます。 親子ノードの場合、共通のフィルター/ハンドラーを親に提供できます。これは、すべての子ノードのデフォルトとして処理されます。

前述のように、イベント中の処理は実行されるフィルターであり、イベントバブリングフェーズ中はハンドラーが実行されます。 すべてのハンドラーとフィルターは、パッケージ javafx.eventEventHandler インターフェースを実装します。

イベントフィルターの追加と削除

イベントフィルターをノードに追加するには、 Node クラスの* addEventFilter()*メソッドを使用してこのフィルターを登録する必要があります。

//Creating the mouse event handler
EventHandler<MouseEvent> eventHandler = new EventHandler<MouseEvent>() {
   @Override
   public void handle(MouseEvent e) {
      System.out.println("Hello World");
      circle.setFill(Color.DARKSLATEBLUE);
   }
};
//Adding event Filter
Circle.addEventFilter(MouseEvent.MOUSE_CLICKED, eventHandler);

同様に、以下に示すようにメソッドremoveEventFilter()を使用してフィルターを削除することができます-

circle.removeEventFilter(MouseEvent.MOUSE_CLICKED, eventHandler);

イベント処理の例

以下は、イベントフィルターを使用したJavaFXでのイベント処理を示す例です。 このコードを EventFiltersExample.java という名前のファイルに保存します。

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.event.EventHandler;

import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;

import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class EventFiltersExample extends Application {
   @Override
   public void start(Stage stage) {
     //Drawing a Circle
      Circle circle = new Circle();

     //Setting the position of the circle
      circle.setCenterX(300.0f);
      circle.setCenterY(135.0f);

     //Setting the radius of the circle
      circle.setRadius(25.0f);

     //Setting the color of the circle
      circle.setFill(Color.BROWN);

     //Setting the stroke width of the circle
      circle.setStrokeWidth(20);

     //Setting the text
      Text text = new Text("Click on the circle to change its color");

     //Setting the font of the text
      text.setFont(Font.font(null, FontWeight.BOLD, 15));

     //Setting the color of the text
      text.setFill(Color.CRIMSON);

     //setting the position of the text
      text.setX(150);
      text.setY(50);

     //Creating the mouse event handler
      EventHandler<MouseEvent> eventHandler = new EventHandler<MouseEvent>() {
         @Override
         public void handle(MouseEvent e) {
            System.out.println("Hello World");
            circle.setFill(Color.DARKSLATEBLUE);
         }
      };
     //Registering the event filter
      circle.addEventFilter(MouseEvent.MOUSE_CLICKED, eventHandler);

     //Creating a Group object
      Group root = new Group(circle, text);

     //Creating a scene object
      Scene scene = new Scene(root, 600, 300);

     //Setting the fill color to the scene
      scene.setFill(Color.LAVENDER);

     //Setting title to the Stage
      stage.setTitle("Event Filters Example");

     //Adding scene to the stage
      stage.setScene(scene);

     //Displaying the contents of the stage
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

次のコマンドを使用して、コマンドプロンプトから保存したJavaファイルをコンパイルして実行します。

javac EventFiltersExample.java
java EventFiltersExample

実行時に、上記のプログラムは以下に示すようにJavaFXウィンドウを生成します。

色の変更

イベントハンドラーの追加と削除

ノードにイベントハンドラーを追加するには、以下に示すように、 Node クラスの* addEventHandler()*メソッドを使用してこのハンドラーを登録する必要があります。

//Creating the mouse event handler
EventHandler<javafx.scene.input.MouseEvent> eventHandler =
   new EventHandler<javafx.scene.input.MouseEvent>() {

   @Override
   public void handle(javafx.scene.input.MouseEvent e) {
      System.out.println("Hello World");
      circle.setFill(Color.DARKSLATEBLUE);
   }
};
//Adding the event handler
circle.addEventHandler(javafx.scene.input.MouseEvent.MOUSE_CLICKED, eventHandler);

同様に、以下に示すようにメソッドremoveEventHandler()を使用してイベントハンドラを削除することができます-

circle.removeEventHandler(MouseEvent.MOUSE_CLICKED, eventHandler);

次のプログラムは、イベントハンドラーを使用したJavaFXでのイベント処理を示す例です。

このコードを EventHandlersExample.java という名前のファイルに保存します。

import javafx.animation.RotateTransition;
import javafx.application.Application;
import javafx.event.EventHandler;

import javafx.scene.Group;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;

import javafx.scene.shape.Box;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.transform.Rotate;
import javafx.stage.Stage;
import javafx.util.Duration;

public class EventHandlersExample extends Application {

   @Override
   public void start(Stage stage) {
     //Drawing a Box
      Box box = new Box();

     //Setting the properties of the Box
      box.setWidth(150.0);
      box.setHeight(150.0);
      box.setDepth(100.0);

     //Setting the position of the box
      box.setTranslateX(350);
      box.setTranslateY(150);
      box.setTranslateZ(50);

     //Setting the text
      Text text = new Text("Type any letter to rotate the box,
         and click on the box to stop the rotation");

     //Setting the font of the text
      text.setFont(Font.font(null, FontWeight.BOLD, 15));

     //Setting the color of the text
      text.setFill(Color.CRIMSON);

     //setting the position of the text
      text.setX(20);
      text.setY(50);

     //Setting the material of the box
      PhongMaterial material = new PhongMaterial();
      material.setDiffuseColor(Color.DARKSLATEBLUE);

     //Setting the diffuse color material to box
      box.setMaterial(material);

     //Setting the rotation animation to the box
      RotateTransition rotateTransition = new RotateTransition();

     //Setting the duration for the transition
      rotateTransition.setDuration(Duration.millis(1000));

     //Setting the node for the transition
      rotateTransition.setNode(box);

     //Setting the axis of the rotation
      rotateTransition.setAxis(Rotate.Y_AXIS);

     //Setting the angle of the rotation
      rotateTransition.setByAngle(360);

     //Setting the cycle count for the transition
      rotateTransition.setCycleCount(50);

     //Setting auto reverse value to false
      rotateTransition.setAutoReverse(false);

     //Creating a text filed
      TextField textField = new TextField();

     //Setting the position of the text field
      textField.setLayoutX(50);
      textField.setLayoutY(100);

     //Handling the key typed event
      EventHandler<KeyEvent> eventHandlerTextField = new EventHandler<KeyEvent>() {
         @Override
         public void handle(KeyEvent event) {
           //Playing the animation
            rotateTransition.play();
         }
      };
     //Adding an event handler to the text feld
      textField.addEventHandler(KeyEvent.KEY_TYPED, eventHandlerTextField);

     //Handling the mouse clicked event(on box)
      EventHandler<javafx.scene.input.MouseEvent> eventHandlerBox =
         new EventHandler<javafx.scene.input.MouseEvent>() {

         @Override
         public void handle(javafx.scene.input.MouseEvent e) {
            rotateTransition.stop();
         }
      };
     //Adding the event handler to the box
      box.addEventHandler(javafx.scene.input.MouseEvent.MOUSE_CLICKED, eventHandlerBox);

     //Creating a Group object
      Group root = new Group(box, textField, text);

     //Creating a scene object
      Scene scene = new Scene(root, 600, 300);

     //Setting camera
      PerspectiveCamera camera = new PerspectiveCamera(false);
      camera.setTranslateX(0);
      camera.setTranslateY(0);
      camera.setTranslateZ(0);
      scene.setCamera(camera);

     //Setting title to the Stage
      stage.setTitle("Event Handlers Example");

     //Adding scene to the stage
      stage.setScene(scene);

     //Displaying the contents of the stage
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

次のコマンドを使用して、コマンドプロンプトから保存したJavaファイルをコンパイルして実行します。

javac EventHandlersExample.java
java EventHandlersExample

実行すると、上記のプログラムは、以下に示すようにテキストフィールドと3Dボックスを表示するJavaFXウィンドウを生成します-

テキストフィールド

ここで、テキストフィールドに文字を入力すると、3Dボックスがx軸に沿って回転し始めます。 もう一度ボックスをクリックすると、回転が停止します。

イベント処理に便利なメソッドを使用する

JavaFXの一部のクラスは、イベントハンドラープロパティを定義します。 それぞれのセッターメソッドを使用してこれらのプロパティに値を設定することにより、イベントハンドラーに登録できます。 これらのメソッドは、便利なメソッドとして知られています。

これらのメソッドのほとんどは、Node、Scene、Windowなどのクラスに存在し、それらのすべてのサブクラスで使用できます。

たとえば、マウスイベントリスナーをボタンに追加するには、以下に示すように便利なメソッド* setOnMouseClicked()*を使用できます。

playButton.setOnMouseClicked((new EventHandler<MouseEvent>() {
   public void handle(MouseEvent event) {
      System.out.println("Hello World");
      pathTransition.play();
   }
}));

次のプログラムは、便利なメソッドを使用したJavaFXでのイベント処理を示す例です。

このコードを ConvinienceMethodsExample.java という名前のファイルに保存します。

import javafx.animation.PathTransition;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.event.EventHandler;

import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;

import javafx.scene.shape.Circle;
import javafx.scene.shape.LineTo;
import javafx.scene.shape.MoveTo;
import javafx.scene.shape.Path;
import javafx.stage.Stage;
import javafx.util.Duration;

public class ConvinienceMethodsExample extends Application {
   @Override
   public void start(Stage stage) {
     //Drawing a Circle
      Circle circle = new Circle();

     //Setting the position of the circle
      circle.setCenterX(300.0f);
      circle.setCenterY(135.0f);

     //Setting the radius of the circle
      circle.setRadius(25.0f);

     //Setting the color of the circle
      circle.setFill(Color.BROWN);

     //Setting the stroke width of the circle
      circle.setStrokeWidth(20);

     //Creating a Path
      Path path = new Path();

     //Moving to the staring point
      MoveTo moveTo = new MoveTo(208, 71);

     //Creating 1st line
      LineTo line1 = new LineTo(421, 161);

     //Creating 2nd line
      LineTo line2 = new LineTo(226,232);

     //Creating 3rd line
      LineTo line3 = new LineTo(332,52);

     //Creating 4th line
      LineTo line4 = new LineTo(369, 250);

     //Creating 5th line
      LineTo line5 = new LineTo(208, 71);

     //Adding all the elements to the path
      path.getElements().add(moveTo);
      path.getElements().addAll(line1, line2, line3, line4, line5);

     //Creating the path transition
      PathTransition pathTransition = new PathTransition();

     //Setting the duration of the transition
      pathTransition.setDuration(Duration.millis(1000));

     //Setting the node for the transition
      pathTransition.setNode(circle);

     //Setting the path for the transition
      pathTransition.setPath(path);

     //Setting the orientation of the path
      pathTransition.setOrientation(
         PathTransition.OrientationType.ORTHOGONAL_TO_TAN GENT);

     //Setting the cycle count for the transition
      pathTransition.setCycleCount(50);

     //Setting auto reverse value to true
      pathTransition.setAutoReverse(false);

     //Creating play button
      Button playButton = new Button("Play");
      playButton.setLayoutX(300);
      playButton.setLayoutY(250);

      circle.setOnMouseClicked (new EventHandler<javafx.scene.input.MouseEvent>() {
         @Override
         public void handle(javafx.scene.input.MouseEvent e) {
            System.out.println("Hello World");
            circle.setFill(Color.DARKSLATEBLUE);
         }
      });
      playButton.setOnMouseClicked((new EventHandler<MouseEvent>() {
         public void handle(MouseEvent event) {
            System.out.println("Hello World");
            pathTransition.play();
         }
      }));

     //Creating stop button
      Button stopButton = new Button("stop");
      stopButton.setLayoutX(250);
      stopButton.setLayoutY(250);

      stopButton.setOnMouseClicked((new EventHandler<MouseEvent>() {
         public void handle(MouseEvent event) {
            System.out.println("Hello World");
            pathTransition.stop();
         }
      }));
     //Creating a Group object
      Group root = new Group(circle, playButton, stopButton);

     //Creating a scene object
      Scene scene = new Scene(root, 600, 300);
      scene.setFill(Color.LAVENDER);

     //Setting title to the Stage
      stage.setTitle("Convenience Methods Example");

     //Adding scene to the stage
      stage.setScene(scene);

     //Displaying the contents of the stage
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

次のコマンドを使用して、コマンドプロンプトから保存したJavaファイルをコンパイルして実行します。

javac ConvinienceMethodsExample.java
java ConvinienceMethodsExample

実行時に、上記のプログラムは以下に示すようにJavaFXウィンドウを生成します。 ここで、再生ボタンをクリックしてアニメーションを開始し、停止ボタンをクリックしてアニメーションを停止します。

便利な方法