Revision 1 as of 2016-11-17 05:50:34

Clear message
Locked History Actions

JavaFX/GraphicsWithRegions

リージョン(ペイン)と共にシーングラフを使う

この方法が意外に思いつかないし、記述のあるウェブもなかなか見つけられない。わかってしまえば簡単だが。

import static java.lang.Math.*;

import java.util.*;

import javafx.animation.*;
import javafx.application.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.paint.*;
import javafx.scene.shape.*;
import javafx.stage.*;

public class GraphicsWithRegions extends Application {

  private Circle ball;
  private double direction;
  private Random random = new Random();
  private double speed = 10;
  @Override
  
  public void start(final Stage primaryStage) {

    ball = new Circle(100, 100, 20);
    ball.setFill(Color.BLUE);
    direction = 2 * PI * random.nextDouble();

    Group group = new Group(ball);
    Pane pane = new Pane(group);

    BorderPane border = new BorderPane();
    border.setCenter(pane);
    border.setTop(new TextArea("top area"));
    border.setBottom(new TextField("bottom field"));
    final Scene scene = new Scene(border, 800, 600, Color.BLACK);
    primaryStage.setScene(scene);
    primaryStage.show();

    ball.setCenterX(pane.getWidth() / 2);
    ball.setCenterY(pane.getHeight() / 2);
    
    new AnimationTimer() {
      @Override
      public void handle(long now) {
        double x = ball.getCenterX();
        double y = ball.getCenterY();
        double newDirection = random.nextDouble() * PI;
        
        if (y < 0) {
          direction = newDirection;
        } else if (pane.getWidth() < x) {
          direction = newDirection + PI * 0.5;
        } else if (pane.getHeight() < y) {
          direction = newDirection + PI;
        } else if (x < 0) {
          direction = newDirection + PI * 1.5;
        }

        ball.setCenterX(x + speed * cos(direction));
        ball.setCenterY(y + speed * sin(direction));
      }
    }.start();
  }

  public static void main(String[] args) {
    launch(args);
  }
}

参考