for my Java coursework I have to create a grid based animation. Basically I currently have a 2d array containing certain values, which change each time the program is run. For example it could be a 20x20 2d array, or a 32x32 etc. Inside the array certain values are stored, chars represent animals, and numbers represent food. The animals smell the food and then move towards the food after each cycle of the program, hence their position in the array change after each cycle. How the program works isn't really relevant to the question I'm asking.
Basically I now have to implement this in JavaFX (it currently works in the console, displaying the array as a grid each cycle). I was just wondering which control would be best to use in JavaFX to display a 2d array, or if perhaps someone could point me in the right direction of how to start coding this?
I'm new to java (and JavaFX) so am not sure of which controls to use...
I wouldn't use a control. I'd rather create a node for each of the items in the array and put them on the scene. Something like this:
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class NodeDemo extends Application {
private double sceneWidth = 1024;
private double sceneHeight = 768;
private int n = 10;
private int m = 10;
double gridWidth = sceneWidth / n;
double gridHeight = sceneHeight / m;
MyNode[][] playfield = new MyNode[n][m];
#Override
public void start(Stage primaryStage) {
Group root = new Group();
// initialize playfield
for( int i=0; i < n; i++) {
for( int j=0; j < m; j++) {
// create node
MyNode node = new MyNode( "Item " + i + "/" + j, i * gridWidth, j * gridHeight, gridWidth, gridHeight);
// add node to group
root.getChildren().add( node);
// add to playfield for further reference using an array
playfield[i][j] = node;
}
}
Scene scene = new Scene( root, sceneWidth, sceneHeight);
primaryStage.setScene( scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
public static class MyNode extends StackPane {
public MyNode( String name, double x, double y, double width, double height) {
// create rectangle
Rectangle rectangle = new Rectangle( width, height);
rectangle.setStroke(Color.BLACK);
rectangle.setFill(Color.LIGHTBLUE);
// create label
Label label = new Label( name);
// set position
setTranslateX( x);
setTranslateY( y);
getChildren().addAll( rectangle, label);
}
}
}
This way you can create animated movement of the nodes easily with a PathTransition. Like this shuffle mechanism:
import java.util.Random;
import javafx.animation.Animation.Status;
import javafx.animation.PathTransition;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.LineTo;
import javafx.scene.shape.MoveTo;
import javafx.scene.shape.Path;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class NodeDemo extends Application {
private double sceneWidth = 1024;
private double sceneHeight = 768;
private int n = 10;
private int m = 10;
double gridWidth = sceneWidth / n;
double gridHeight = sceneHeight / m;
MyNode[][] playfield = new MyNode[n][m];
#Override
public void start(Stage primaryStage) {
Group root = new Group();
// initialize playfield
for( int i=0; i < n; i++) {
for( int j=0; j < m; j++) {
// create node
MyNode node = new MyNode( "Item " + i + "/" + j, i * gridWidth, j * gridHeight, gridWidth, gridHeight);
// add node to group
root.getChildren().add( node);
// add to playfield for further reference using an array
playfield[i][j] = node;
}
}
Scene scene = new Scene( root, sceneWidth, sceneHeight);
primaryStage.setScene( scene);
primaryStage.show();
animate();
}
private void animate() {
Random random = new Random();
int ai = random.nextInt(n);
int aj = random.nextInt(m);
int bi = random.nextInt(n);
int bj = random.nextInt(m);
// make sure that A and B are never the same
if( ai == bi && aj == bj) {
ai++;
if( ai >= n)
ai = 0;
}
MyNode nodeA = playfield[ai][aj];
nodeA.toFront();
MyNode nodeB = playfield[bi][bj];
nodeB.toFront();
// swap on array to keep array consistent
playfield[ai][aj] = nodeB;
playfield[bi][bj] = nodeA;
// A -> B
Path pathA = new Path();
pathA.getElements().add (new MoveTo ( nodeA.getTranslateX() + nodeA.getBoundsInParent().getWidth() / 2.0, nodeA.getTranslateY() + nodeA.getBoundsInParent().getHeight() / 2.0));
pathA.getElements().add (new LineTo( nodeB.getTranslateX() + nodeB.getBoundsInParent().getWidth() / 2.0, nodeB.getTranslateY() + nodeB.getBoundsInParent().getHeight() / 2.0));
PathTransition pathTransitionA = new PathTransition();
pathTransitionA.setDuration(Duration.millis(1000));
pathTransitionA.setNode( nodeA);
pathTransitionA.setPath(pathA);
pathTransitionA.play();
// B -> A
Path pathB = new Path();
pathB.getElements().add (new MoveTo ( nodeB.getTranslateX() + nodeB.getBoundsInParent().getWidth() / 2.0, nodeB.getTranslateY() + nodeB.getBoundsInParent().getHeight() / 2.0));
pathB.getElements().add (new LineTo( nodeA.getTranslateX() + nodeA.getBoundsInParent().getWidth() / 2.0, nodeA.getTranslateY() + nodeA.getBoundsInParent().getHeight() / 2.0));
PathTransition pathTransitionB = new PathTransition();
pathTransitionB.setDuration(Duration.millis(1000));
pathTransitionB.setNode( nodeB);
pathTransitionB.setPath(pathB);
pathTransitionB.play();
pathTransitionA.setOnFinished( new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
if( pathTransitionB.getStatus() == Status.RUNNING)
return;
animate();
}
});
pathTransitionB.setOnFinished( new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
if( pathTransitionA.getStatus() == Status.RUNNING)
return;
animate();
}
});
}
public static void main(String[] args) {
launch(args);
}
public static class MyNode extends StackPane {
public MyNode( String name, double x, double y, double width, double height) {
// create rectangle
Rectangle rectangle = new Rectangle( width, height);
rectangle.setStroke(Color.BLACK);
rectangle.setFill(Color.LIGHTBLUE);
// create label
Label label = new Label( name);
// set position
setTranslateX( x);
setTranslateY( y);
getChildren().addAll( rectangle, label);
}
}
}
And here's an example about how you could handle the cells via subclassing. But that's just one way to do it:
public class NodeDemo extends Application {
private double sceneWidth = 1024;
private double sceneHeight = 768;
private int n = 10;
private int m = 10;
double gridWidth = sceneWidth / n;
double gridHeight = sceneHeight / m;
MyNode[][] playfield = new MyNode[n][m];
#Override
public void start(Stage primaryStage) {
Group root = new Group();
// initialize playfield
for( int i=0; i < n; i++) {
for( int j=0; j < m; j++) {
MyNode node = null;
// create bug
if( i == 0 && j == 0) {
node = new Bug( "Bug", Color.ORANGE, i, j);
}
// create food
else if( i == 5 && j == 5) {
node = new Food( "Food", Color.GREEN, i, j);
}
// create obstacle
else if( i == 3 && j == 3) {
node = new Obstacle( "Obstacle", Color.GRAY, i, j);
}
// add node to group
if( node != null) {
root.getChildren().add( node);
// add to playfield for further reference using an array
playfield[i][j] = node;
}
}
}
Scene scene = new Scene( root, sceneWidth, sceneHeight);
primaryStage.setScene( scene);
primaryStage.show();
// move bugs
animate();
}
private void animate() {
// TODO
}
public static void main(String[] args) {
launch(args);
}
private class Food extends MyNode {
public Food(String name, Color color, double x, double y) {
super(name, color, x, y);
}
}
private class Obstacle extends MyNode {
public Obstacle(String name, Color color, double x, double y) {
super(name, color, x, y);
}
}
private class Bug extends MyNode {
public Bug(String name, Color color, double x, double y) {
super(name, color, x, y);
}
}
private class MyNode extends StackPane {
public MyNode( String name, Color color, double x, double y) {
// create rectangle
Rectangle rectangle = new Rectangle( gridWidth, gridHeight);
rectangle.setStroke( color);
rectangle.setFill( color.deriveColor(1, 1, 1, 0.7));
// create label
Label label = new Label( name);
// set position
setTranslateX( x * gridWidth);
setTranslateY( y * gridHeight);
getChildren().addAll( rectangle, label);
}
}
}
You can start looking at the "Getting Started" section at the documentation. Focus on the simple examples like the HelloWorld and LoginForm sample programs.
For you structure you'll probably want to use a GridPane.
Related
I created a star plotting application to plot labels for a 3d star plotter so that the labels are mapped local to scene. I wanted to do this so that whenever I rotate the starfield, the labels are always facing forward and don't rotate with the individual stars (annoying because they can't be read).
Now this works very well until I added a control panel above it. In the application below, if the control panel is not present, then labels track with the position of the stars. But with the control panel, the labels are y-offset by the size of the control panel height.
The issue is that the "mousePosY = me.getSceneY();" returns the mouse position of the scene itself and not the defined subScene. I had thought that the "subScene.setOnMouseDragged((MouseEvent me) -> {" would have given me the position of the mouse relative to the subScene and not the scene.
Is there any way to fix this so that the returned X,Y position is for the subScene only?
The following code is a very cutdown version of my application that shows the actual issue itself.
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Point3D;
import javafx.scene.*;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Background;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;
import javafx.scene.shape.Sphere;
import javafx.scene.text.Font;
import javafx.scene.transform.Rotate;
import javafx.scene.transform.Translate;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;
import java.util.HashMap;
import java.util.Random;
import static org.fxyz3d.geometry.MathUtils.clamp;
/**
* example for flat labels
*/
#Slf4j
public class StarFieldExample extends Application {
public static final int SCALE_X = 510;
public static final int SCALE_Y = 540;
public static final int SCALE_Z = 0;
final double sceneWidth = 600;
final double sceneHeight = 600;
private double mousePosX;
private double mousePosY;
private double mouseOldX;
private double mouseOldY;
private double mouseDeltaX;
private double mouseDeltaY;
private final Font font = new Font("arial", 10);
// We'll use custom Rotate transforms to manage the coordinate conversions
private final Rotate rotateX = new Rotate(0, Rotate.X_AXIS);
private final Rotate rotateY = new Rotate(0, Rotate.Y_AXIS);
private final Rotate rotateZ = new Rotate(0, Rotate.Z_AXIS);
private final Group root = new Group();
private final Group world = new Group(); //all 3D nodes in scene
private final Group labelGroup = new Group(); //all generic 3D labels
//All shapes and labels linked via hash for easy update during camera movement
private final HashMap<Node, Label> shape3DToLabel = new HashMap<>();
private SubScene subScene;
////// support
private final Random random = new Random();
private final static double RADIUS_MAX = 7;
private final static double X_MAX = 300;
private final static double Y_MAX = 300;
private final static double Z_MAX = 300;
private final Label scaleLabel = new Label("Scale: 5 ly");
public Pane createStarField() {
// attach our custom rotation transforms so we can update the labels dynamically
world.getTransforms().addAll(rotateX, rotateY, rotateZ);
subScene = new SubScene(world, sceneWidth, sceneHeight, true, SceneAntialiasing.BALANCED);
subScene.setFill(Color.BLACK);
PerspectiveCamera camera = new PerspectiveCamera(true);
camera.setNearClip(0.1);
camera.setFarClip(10000.0);
camera.setTranslateZ(-1000);
subScene.setCamera(camera);
Group sceneRoot = new Group(subScene);
sceneRoot.getChildren().add(labelGroup);
generateRandomStars(5);
handleMouseEvents();
// add to the 2D portion of this component
Pane pane = new Pane();
pane.setPrefSize(sceneWidth, sceneHeight);
pane.setMaxSize(Pane.USE_COMPUTED_SIZE, Pane.USE_COMPUTED_SIZE);
pane.setMinSize(Pane.USE_COMPUTED_SIZE, Pane.USE_COMPUTED_SIZE);
pane.setBackground(Background.EMPTY);
pane.getChildren().add(sceneRoot);
pane.setPickOnBounds(true);
subScene.widthProperty().bind(pane.widthProperty());
subScene.heightProperty().bind(pane.heightProperty());
Platform.runLater(this::updateLabels);
return (pane);
}
private void handleMouseEvents() {
subScene.setOnMousePressed((MouseEvent me) -> {
mousePosX = me.getSceneX();
mousePosY = me.getSceneY();
mouseOldX = me.getSceneX();
mouseOldY = me.getSceneY();
}
);
subScene.setOnMouseDragged((MouseEvent me) -> {
mouseOldX = mousePosX;
mouseOldY = mousePosY;
mousePosX = me.getSceneX();
mousePosY = me.getSceneY();
mouseDeltaX = (mousePosX - mouseOldX);
mouseDeltaY = (mousePosY - mouseOldY);
double modifier = 5.0;
double modifierFactor = 0.1;
if (me.isPrimaryButtonDown()) {
if (me.isAltDown()) { //roll
rotateZ.setAngle(((rotateZ.getAngle() + mouseDeltaX * modifierFactor * modifier * 2.0) % 360 + 540) % 360 - 180); // +
} else {
rotateY.setAngle(((rotateY.getAngle() + mouseDeltaX * modifierFactor * modifier * 2.0) % 360 + 540) % 360 - 180); // +
rotateX.setAngle(
clamp(
(((rotateX.getAngle() - mouseDeltaY * modifierFactor * modifier * 2.0) % 360 + 540) % 360 - 180),
-60,
60
)
); // -
}
}
updateLabels();
}
);
}
public void generateRandomStars(int numberStars) {
for (int i = 0; i < numberStars; i++) {
double radius = random.nextDouble() * RADIUS_MAX;
Color color = randomColor();
double x = random.nextDouble() * X_MAX * 2 / 3 * (random.nextBoolean() ? 1 : -1);
double y = random.nextDouble() * Y_MAX * 2 / 3 * (random.nextBoolean() ? 1 : -1);
double z = random.nextDouble() * Z_MAX * 2 / 3 * (random.nextBoolean() ? 1 : -1);
String labelText = "Star " + i;
boolean fadeFlag = random.nextBoolean();
createSphereLabel(radius, x, y, z, color, labelText, fadeFlag);
}
//Add to hashmap so updateLabels() can manage the label position
scaleLabel.setFont(new Font("Arial", 15));
scaleLabel.setTextFill(Color.WHEAT);
scaleLabel.setTranslateX(SCALE_X);
scaleLabel.setTranslateY(SCALE_Y);
scaleLabel.setTranslateZ(SCALE_Z);
labelGroup.getChildren().add(scaleLabel);
log.info("shapes:{}", shape3DToLabel.size());
}
private Color randomColor() {
int r = random.nextInt(255);
int g = random.nextInt(255);
int b = random.nextInt(255);
return Color.rgb(r, g, b);
}
private void createSphereLabel(double radius, double x, double y, double z, Color color, String labelText, boolean fadeFlag) {
Sphere sphere = new Sphere(radius);
sphere.setTranslateX(x);
sphere.setTranslateY(y);
sphere.setTranslateZ(z);
sphere.setMaterial(new PhongMaterial(color));
//add our nodes to the group that will later be added to the 3D scene
world.getChildren().add(sphere);
Label label = new Label(labelText);
label.setTextFill(color);
label.setFont(font);
labelGroup.getChildren().add(label);
//Add to hashmap so updateLabels() can manage the label position
shape3DToLabel.put(sphere, label);
}
private void updateLabels() {
shape3DToLabel.forEach((node, label) -> {
Point3D coordinates = node.localToScene(Point3D.ZERO, true);
//Clipping Logic
//if coordinates are outside of the scene it could
//stretch the screen so don't transform them
double x = coordinates.getX();
double y = coordinates.getY();
// is it left of the view?
if (x < 0) {
x = 0;
}
// is it right of the view?
if ((x + label.getWidth() + 5) > subScene.getWidth()) {
x = subScene.getWidth() - (label.getWidth() + 5);
}
// is it above the view?
if (y < 0) {
y = 0;
}
// is it below the view
if ((y + label.getHeight()) > subScene.getHeight()) {
y = subScene.getHeight() - (label.getHeight() + 5);
}
//update the local transform of the label.
label.getTransforms().setAll(new Translate(x, y));
});
scaleLabel.setTranslateX(SCALE_X);
scaleLabel.setTranslateY(SCALE_Y);
scaleLabel.setTranslateZ(SCALE_Z);
}
//////////////////////////////////
#Override
public void start(Stage primaryStage) throws Exception {
Pane controls = createControls();
Pane pane = createStarField();
VBox vBox = new VBox(
controls,
pane
);
root.getChildren().add(vBox);
Scene scene = new Scene(root, sceneWidth, sceneHeight - 40);
primaryStage.setTitle("2D Labels over 3D SubScene");
primaryStage.setScene(scene);
primaryStage.show();
}
private VBox createControls() {
VBox controls = new VBox(10, new Button("Button"));
controls.setPadding(new Insets(10));
return controls;
}
public static void main(String[] args) {
launch(args);
}
}
I broke this down into a simpler problem relating mouse offset, solved that, and then worked that solution into here.
The key issue is that I assumed that the mouse event (x,y) positions would be zero offset to the SubScene, and in reality, they are relative to the containing scene. I had to calculate the bounds of the component relative to the parent. Having the actual location of the SubScene in the layout of the larger application allows me to calculate the corrected (x,y) positions.
Here is the answer:
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Bounds;
import javafx.geometry.Insets;
import javafx.geometry.Point3D;
import javafx.scene.*;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Background;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;
import javafx.scene.shape.Sphere;
import javafx.scene.text.Font;
import javafx.scene.transform.Rotate;
import javafx.scene.transform.Translate;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import static org.fxyz3d.geometry.MathUtils.clamp;
/**
* example for flat labels
*/
#Slf4j
public class StarFieldExample extends Application {
public static final int SCALE_X = 510;
public static final int SCALE_Y = 540;
public static final int SCALE_Z = 0;
final double sceneWidth = 600;
final double sceneHeight = 600;
private double mousePosX;
private double mousePosY;
private double mouseOldX;
private double mouseOldY;
private double mouseDeltaX;
private double mouseDeltaY;
private final Font font = new Font("arial", 10);
// We'll use custom Rotate transforms to manage the coordinate conversions
private final Rotate rotateX = new Rotate(0, Rotate.X_AXIS);
private final Rotate rotateY = new Rotate(0, Rotate.Y_AXIS);
private final Rotate rotateZ = new Rotate(0, Rotate.Z_AXIS);
private final Group root = new Group();
private final Group world = new Group(); //all 3D nodes in scene
private final Group labelGroup = new Group(); //all generic 3D labels
//All shapes and labels linked via hash for easy update during camera movement
private final Map<Node, Label> shape3DToLabel = new HashMap<>();
private SubScene subScene;
////// support
private final Random random = new Random();
private final static double RADIUS_MAX = 7;
private final static double X_MAX = 300;
private final static double Y_MAX = 300;
private final static double Z_MAX = 300;
Pane pane;
private final Label scaleLabel = new Label("Scale: 5 ly");
public Pane createStarField() {
PerspectiveCamera camera = setupPerspectiveCamera();
// attach our custom rotation transforms so we can update the labels dynamically
world.getTransforms().addAll(rotateX, rotateY, rotateZ);
subScene = new SubScene(world, sceneWidth, sceneHeight, true, SceneAntialiasing.BALANCED);
subScene.setFill(Color.BLACK);
subScene.setCamera(camera);
Group sceneRoot = new Group(subScene);
sceneRoot.getChildren().add(labelGroup);
generateRandomStars(5);
// add to the 2D portion of this component
pane = new Pane();
pane.setPrefSize(sceneWidth, sceneHeight);
pane.setMaxSize(Pane.USE_COMPUTED_SIZE, Pane.USE_COMPUTED_SIZE);
pane.setMinSize(Pane.USE_COMPUTED_SIZE, Pane.USE_COMPUTED_SIZE);
pane.setBackground(Background.EMPTY);
pane.getChildren().add(sceneRoot);
pane.setPickOnBounds(true);
subScene.widthProperty().bind(pane.widthProperty());
subScene.heightProperty().bind(pane.heightProperty());
Platform.runLater(this::updateLabels);
handleMouseEvents();
return (pane);
}
#NotNull
private PerspectiveCamera setupPerspectiveCamera() {
PerspectiveCamera camera = new PerspectiveCamera(true);
camera.setNearClip(0.1);
camera.setFarClip(10000.0);
camera.setTranslateZ(-1000);
return camera;
}
private void handleMouseEvents() {
subScene.setOnMousePressed((MouseEvent me) -> {
mousePosX = me.getSceneX();
mousePosY = me.getSceneY();
mouseOldX = me.getSceneX();
mouseOldY = me.getSceneY();
}
);
subScene.setOnMouseDragged((MouseEvent me) -> {
mouseOldX = mousePosX;
mouseOldY = mousePosY;
mousePosX = me.getSceneX();
mousePosY = me.getSceneY();
mouseDeltaX = (mousePosX - mouseOldX);
mouseDeltaY = (mousePosY - mouseOldY);
double modifier = 5.0;
double modifierFactor = 0.1;
if (me.isPrimaryButtonDown()) {
if (me.isAltDown()) { //roll
rotateZ.setAngle(((rotateZ.getAngle() + mouseDeltaX * modifierFactor * modifier * 2.0) % 360 + 540) % 360 - 180); // +
} else {
rotateY.setAngle(((rotateY.getAngle() + mouseDeltaX * modifierFactor * modifier * 2.0) % 360 + 540) % 360 - 180); // +
rotateX.setAngle(
clamp(
(((rotateX.getAngle() - mouseDeltaY * modifierFactor * modifier * 2.0) % 360 + 540) % 360 - 180),
-60,
60
)
); // -
}
}
updateLabels();
}
);
}
private void updateLabels() {
shape3DToLabel.forEach((node, label) -> {
Point3D coordinates = node.localToScene(Point3D.ZERO, true);
//Clipping Logic
//if coordinates are outside of the scene it could
//stretch the screen so don't transform them
double xs = coordinates.getX();
double ys = coordinates.getY();
Bounds ofParent = pane.getBoundsInParent();
double x = xs - ofParent.getMinX();
double y = ys - ofParent.getMinY();
// is it left of the view?
if (x < 0) {
x = 0;
}
// is it right of the view?
if ((x + label.getWidth() + 5) > subScene.getWidth()) {
x = subScene.getWidth() - (label.getWidth() + 5);
}
// is it above the view?
if (y < 0) {
y = 0;
}
// is it below the view
if ((y + label.getHeight()) > subScene.getHeight()) {
y = subScene.getHeight() - (label.getHeight() + 5);
}
//update the local transform of the label.
label.getTransforms().setAll(new Translate(x, y));
});
scaleLabel.setTranslateX(SCALE_X);
scaleLabel.setTranslateY(SCALE_Y);
scaleLabel.setTranslateZ(SCALE_Z);
}
public void generateRandomStars(int numberStars) {
for (int i = 0; i < numberStars; i++) {
double radius = random.nextDouble() * RADIUS_MAX;
Color color = randomColor();
double x = random.nextDouble() * X_MAX * 2 / 3 * (random.nextBoolean() ? 1 : -1);
double y = random.nextDouble() * Y_MAX * 2 / 3 * (random.nextBoolean() ? 1 : -1);
double z = random.nextDouble() * Z_MAX * 2 / 3 * (random.nextBoolean() ? 1 : -1);
String labelText = "Star " + i;
boolean fadeFlag = random.nextBoolean();
createSphereLabel(radius, x, y, z, color, labelText, fadeFlag);
}
//Add to hashmap so updateLabels() can manage the label position
scaleLabel.setFont(new Font("Arial", 15));
scaleLabel.setTextFill(Color.WHEAT);
scaleLabel.setTranslateX(SCALE_X);
scaleLabel.setTranslateY(SCALE_Y);
scaleLabel.setTranslateZ(SCALE_Z);
labelGroup.getChildren().add(scaleLabel);
log.info("shapes:{}", shape3DToLabel.size());
}
private Color randomColor() {
int r = random.nextInt(255);
int g = random.nextInt(255);
int b = random.nextInt(255);
return Color.rgb(r, g, b);
}
private void createSphereLabel(double radius, double x, double y, double z, Color color, String labelText, boolean fadeFlag) {
Sphere sphere = new Sphere(radius);
sphere.setTranslateX(x);
sphere.setTranslateY(y);
sphere.setTranslateZ(z);
sphere.setMaterial(new PhongMaterial(color));
//add our nodes to the group that will later be added to the 3D scene
world.getChildren().add(sphere);
Label label = new Label(labelText);
label.setTextFill(color);
label.setFont(font);
labelGroup.getChildren().add(label);
//Add to hashmap so updateLabels() can manage the label position
shape3DToLabel.put(sphere, label);
}
//////////////////////////////////
#Override
public void start(Stage primaryStage) throws Exception {
Pane controls = createControls();
Pane pane = createStarField();
VBox vBox = new VBox(
controls,
pane
);
root.getChildren().add(vBox);
Scene scene = new Scene(root, sceneWidth, sceneHeight - 40);
primaryStage.setTitle("2D Labels over 3D SubScene");
primaryStage.setScene(scene);
primaryStage.show();
}
private VBox createControls() {
VBox controls = new VBox(10, new Button("Button"));
controls.setPadding(new Insets(10));
return controls;
}
public static void main(String[] args) {
launch(args);
}
}
I'm making an application with javaFX. The application consists of creating a kind of "graph" from the user.
The user through a button creates a node (is created by a circle with JAVAFX figure) and associates it to a variable, repeating the process, creating another node, and so on. Now I need to figure out how to define the node position inside a specially reserved space. Obviously, after creating nodes, through another button, the user creates the arcs (is created by a line connecting two nodes) associated with the nodes, thus defining a graph.
My problem is that I do not understand how to indicate the position of lines that will act as arcs in my graph.
Please help me.I'm not very experienced and I'm trying to tackle this problem.
First of all you need to tell us what is your "reserved space"? If it's a Canvas then you can draw shapes with Canva's GraphicsContext.
Canvas canvas = new Canvas(300, 250);
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.fillOval(10, 60, 30, 30);
gc.fillArc(10, 110, 30, 30, 45, 240, ArcType.OPEN);
Otherwise if you are working inside a pane with layout you need to know if the components are managed or not. For example inside a Pane or AnchorPane the node's automatic layout is disabled, thus you need to specify their layoutX and layoutY by yourself (+ node dimensions) like :
node.setLayoutX(12);
node.setLayoutY(222);
node.setPrefWidth(500);
node.setPrefHeight(500);
If you are using a pane like VBox which manage the layout of it's nodes you need to set the nodes inside the pane to be unmanaged in order for you to apply specific transformations. You can do that just by setting :
node.setManaged(false)
I will not recommend you to use Canvas cause handling the shapes will be very hard, for example if you need to remove something you probably have to clear everything and redraw only the visible shapes.
Well I had some time so here is a small example ( It might not be the optimal solution, but you can take is as a reference)
GraphTest
import java.util.ArrayList;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
public class GraphTest extends Application {
private double orgSceneX, orgSceneY;
private double orgTranslateX, orgTranslateY;
private Group root = new Group();
#Override
public void start(Stage primaryStage) throws Exception {
GraphNode node1 = createNode("A", 100, 100, Color.RED);
GraphNode node2 = createNode("B", 300, 200, Color.GREEN);
GraphNode node3 = createNode("C", 80, 300, Color.PURPLE);
connectNodes(node1, node2, "C1");
connectNodes(node3, node1, "C2");
connectNodes(node3, node2, "C3");
root.getChildren().addAll(node1, node2, node3);
primaryStage.setScene(new Scene(root, 400, 400));
primaryStage.show();
}
private void connectNodes(GraphNode node1, GraphNode node2, String edgeText) {
Line edgeLine = new Line(node1.getCenterX(), node1.getCenterY(), node2.getCenterX(), node2.getCenterY());
Label edgeLabel = new Label(edgeText);
node1.addNeighbor(node2);
node2.addNeighbor(node1);
node1.addEdge(edgeLine, edgeLabel);
node2.addEdge(edgeLine, edgeLabel);
root.getChildren().addAll(edgeLine, edgeLabel);
}
private GraphNode createNode(String nodeName, double xPos, double yPos, Color color) {
GraphNode node = new GraphNode(nodeName, xPos, yPos, color);
node.setOnMousePressed(circleOnMousePressedEventHandler);
node.setOnMouseDragged(circleOnMouseDraggedEventHandler);
return node;
}
EventHandler<MouseEvent> circleOnMousePressedEventHandler = new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent t) {
orgSceneX = t.getSceneX();
orgSceneY = t.getSceneY();
GraphNode node = (GraphNode) t.getSource();
orgTranslateX = node.getTranslateX();
orgTranslateY = node.getTranslateY();
}
};
EventHandler<MouseEvent> circleOnMouseDraggedEventHandler = new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent t) {
double offsetX = t.getSceneX() - orgSceneX;
double offsetY = t.getSceneY() - orgSceneY;
double newTranslateX = orgTranslateX + offsetX;
double newTranslateY = orgTranslateY + offsetY;
GraphNode node = (GraphNode) t.getSource();
node.setTranslateX(newTranslateX);
node.setTranslateY(newTranslateY);
updateLocations(node);
}
};
private void updateLocations(GraphNode node) {
ArrayList<GraphNode> connectedNodes = node.getConnectedNodes();
ArrayList<Line> edgesList = node.getEdges();
for (int i = 0; i < connectedNodes.size(); i++) {
GraphNode neighbor = connectedNodes.get(i);
Line l = edgesList.get(i);
l.setStartX(node.getCenterX());
l.setStartY(node.getCenterY());
l.setEndX(neighbor.getCenterX());
l.setEndY(neighbor.getCenterY());
}
}
public static void main(String[] args) {
launch(args);
}
}
GraphNode
import java.util.ArrayList;
import javafx.beans.binding.DoubleBinding;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
public class GraphNode extends StackPane {
private Circle circle;
private Label text;
private ArrayList<GraphNode> connectedNodesList = new ArrayList<>();
private ArrayList<Line> edgesList = new ArrayList<>();
private ArrayList<Label> edgesLabelList = new ArrayList<>();
private double radius = 50.0;
public GraphNode(String name, double xPos, double yPos, Color color) {
circle = new Circle(radius, color);
text = new Label(name);
text.setTextFill(Color.WHITE);
setLayoutX(xPos);
setLayoutY(yPos);
getChildren().addAll(circle, text);
layout();
}
public void addNeighbor(GraphNode node) {
connectedNodesList.add(node);
}
public void addEdge(Line edgeLine, Label edgeLabel) {
edgesList.add(edgeLine);
edgesLabelList.add(edgeLabel);
// If user move the node we should translate the edge labels as well
// one way of doing that is by make a custom binding to the layoutXProperty as well
// as to layoutYProperty. We will listen for changes to the currentNode translate properties
// and for changes of our neighbor.
edgeLabel.layoutXProperty().bind(new DoubleBinding() {
{
bind(translateXProperty());
bind(connectedNodesList.get(connectedNodesList.size() - 1).translateXProperty());
}
#Override
protected double computeValue() {
// We find the center of the line to translate the text
double width = edgeLine.getEndX() - edgeLine.getStartX();
return edgeLine.getStartX() + width / 2.0;
}
});
edgeLabel.layoutYProperty().bind(new DoubleBinding() {
{
bind(translateYProperty());
bind(connectedNodesList.get(connectedNodesList.size() - 1).translateYProperty());
}
#Override
protected double computeValue() {
double width = edgeLine.getEndY() - edgeLine.getStartY();
return edgeLine.getStartY() + width / 2.0;
}
});
}
public ArrayList<GraphNode> getConnectedNodes() {
return connectedNodesList;
}
public ArrayList<Line> getEdges() {
return edgesList;
}
public double getX() {
return getLayoutX() + getTranslateX();
}
public double getY() {
return getLayoutY() + getTranslateY();
}
public double getCenterX() {
return getX() + radius;
}
public double getCenterY() {
return getY() + radius;
}
}
And the Output would look like that :
You can move the nodes with your mouse and you will see all the labels will follow the shapes locations ( Cicle , Lines )
I have a set of Nodes, Circles, on the stage.
I want to be able to click on one of them and 'select it' (just get a reference to it so I can move it around, change color etc.)
Pane root = new Pane();
root.getChildren().addAll( /* an array of Circle objects */ );
Scene scene = new Scene(root, 500, 500, BACKGROUND_COLOR);
scene.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
// how do I get which Circle I clicked on?
}
});
stage.setTitle(TITLE);
stage.setScene(scene);
stage.show();
I would simply register a listener with each circle itself. Then you already have the reference to the circle with which the listener was registered.
This example pushes the limit a little as to usability, because it has 10,000 circles shown all at once, but it demonstrates the technique:
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.css.PseudoClass;
import javafx.geometry.Point2D;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
public class GridOfCircles extends Application {
private static final PseudoClass SELECTED_P_C = PseudoClass.getPseudoClass("selected");
private final int numColumns = 100 ;
private final int numRows = 100 ;
private final double radius = 4 ;
private final double spacing = 2 ;
private final ObjectProperty<Circle> selectedCircle = new SimpleObjectProperty<>();
private final ObjectProperty<Point2D> selectedLocation = new SimpleObjectProperty<>();
#Override
public void start(Stage primaryStage) {
selectedCircle.addListener((obs, oldSelection, newSelection) -> {
if (oldSelection != null) {
oldSelection.pseudoClassStateChanged(SELECTED_P_C, false);
}
if (newSelection != null) {
newSelection.pseudoClassStateChanged(SELECTED_P_C, true);
}
});
Pane grid = new Pane();
for (int x = 0 ; x < numColumns; x++) {
double gridX = x*(spacing + radius + radius) + spacing ;
grid.getChildren().add(new Line(gridX, 0, gridX, numRows*(spacing + radius + radius)));
}
for (int y = 0; y < numRows ; y++) {
double gridY = y*(spacing + radius + radius) + spacing ;
grid.getChildren().add(new Line(0, gridY, numColumns*(spacing + radius + radius), gridY));
}
for (int x = 0 ; x < numColumns; x++) {
for (int y = 0 ;y < numRows ; y++) {
grid.getChildren().add(createCircle(x, y));
}
}
Label label = new Label();
label.textProperty().bind(Bindings.createStringBinding(() -> {
Point2D loc = selectedLocation.get();
if (loc == null) {
return "" ;
}
return String.format("Location: [%.0f, %.0f]", loc.getX(), loc.getY());
}, selectedLocation));
BorderPane root = new BorderPane(new ScrollPane(grid));
root.setTop(label);
Scene scene = new Scene(root);
scene.getStylesheets().add("grid.css");
primaryStage.setScene(scene);
primaryStage.show();
}
private Circle createCircle(int x, int y) {
Circle circle = new Circle();
circle.getStyleClass().add("intersection");
circle.setCenterX(x * (spacing + radius + radius) + spacing);
circle.setCenterY(y * (spacing + radius + radius) + spacing);
circle.setRadius(radius);
circle.addEventHandler(MouseEvent.MOUSE_CLICKED, e -> {
selectedCircle.set(circle);
selectedLocation.set(new Point2D(x, y));
});
return circle ;
}
public static void main(String[] args) {
launch(args);
}
}
with the file grid.css:
.intersection {
-fx-fill: blue ;
}
.intersection:selected {
-fx-fill: gold ;
}
You can get the reference by using getSource of the MouseEvent.
Example in which you can drag a Circle and any other Node:
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
Circle circle = new Circle( 100,100,50);
circle.setStroke(Color.BLUE);
circle.setFill(Color.BLUE.deriveColor(1, 1, 1, 0.3));
Rectangle rectangle = new Rectangle( 0,0,100,100);
rectangle.relocate(200, 200);
rectangle.setStroke(Color.GREEN);
rectangle.setFill(Color.GREEN.deriveColor(1, 1, 1, 0.3));
Text text = new Text( "Example Text");
text.relocate(300, 300);
Pane root = new Pane();
root.getChildren().addAll(circle, rectangle, text);
MouseGestures mouseGestures = new MouseGestures();
mouseGestures.makeDraggable(circle);
mouseGestures.makeDraggable(rectangle);
mouseGestures.makeDraggable(text);
Scene scene = new Scene(root, 1024, 768);
primaryStage.setScene(scene);
primaryStage.show();
}
public static class MouseGestures {
class DragContext {
double x;
double y;
}
DragContext dragContext = new DragContext();
public void makeDraggable( Node node) {
node.setOnMousePressed( onMousePressedEventHandler);
node.setOnMouseDragged( onMouseDraggedEventHandler);
node.setOnMouseReleased(onMouseReleasedEventHandler);
}
EventHandler<MouseEvent> onMousePressedEventHandler = event -> {
if( event.getSource() instanceof Circle) {
Circle circle = (Circle) (event.getSource());
dragContext.x = circle.getCenterX() - event.getSceneX();
dragContext.y = circle.getCenterY() - event.getSceneY();
} else {
Node node = (Node) (event.getSource());
dragContext.x = node.getTranslateX() - event.getSceneX();
dragContext.y = node.getTranslateY() - event.getSceneY();
}
};
EventHandler<MouseEvent> onMouseDraggedEventHandler = event -> {
if( event.getSource() instanceof Circle) {
Circle circle = (Circle) (event.getSource());
circle.setCenterX( dragContext.x + event.getSceneX());
circle.setCenterY( dragContext.y + event.getSceneY());
} else {
Node node = (Node) (event.getSource());
node.setTranslateX( dragContext.x + event.getSceneX());
node.setTranslateY( dragContext.y + event.getSceneY());
}
};
EventHandler<MouseEvent> onMouseReleasedEventHandler = event -> {
};
}
public static void main(String[] args) {
launch(args);
}
}
I've written a java implementation of Craig Reynolds Boids. I recently updated each object to be represented by a .png image. Ever since I've been having the display issue in the image.
What's the best way to fix the issue?
I've tried using a Polygon but when one of my coordinates is a negative the triangle doesn't display properly.
Main Class:
public void paint(final GraphicsContext g) {
new AnimationTimer() {
#Override
public void handle(long now) {
flock.updateBoidsPostion();
g.clearRect(0, 0, width, height);
flock.drawBoids(g);
}
}.start();
}
#Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Boids Flocking Algorithm");
Group root = new Group();
Canvas canvas = new Canvas(width, height);
GraphicsContext gc = canvas.getGraphicsContext2D();
root.getChildren().add(canvas);
primaryStage.setScene(new Scene(root));
primaryStage.show();
paint(gc);
}
Flock:
/**
* Paint each boid comprising the flock the canvas.
* #param g
*/
public void drawBoids(GraphicsContext g) {
for(Boid aBoid : boids) {
aBoid.draw(g);
}
}
Boid:
public void draw(GraphicsContext g) {
//coordinates for the tip of the boid
int x = (int)this.position.xPos;
int y = (int)this.position.yPos;
//Calculate a angle representing the direction of travel.
Rotate r = new Rotate(angle, x, y);
g.setTransform(r.getMxx(), r.getMyx(), r.getMxy(), r.getMyy(), r.getTx(), r.getTy());
g.drawImage(image, x, y);
}
The problem with your code is that you rotate the GraphicsContext, not the image. Or at least you don't rotate the GraphicsContext back after you rotated it.
I was curious about the link you mentioned, i. e. the Boids Pseudocode.
Here's a quick implementation. Drag the rectangle to have the flock follow it.
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.geometry.Point2D;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.stage.Stage;
// Boids implementation in JavaFX
// Pseudo code by Conrad Parker: http://www.kfish.org/boids/pseudocode.html
public class Main extends Application {
int numBoids = 50;
double boidRadius = 10d;
double boidMinDistance = boidRadius * 2d + 5; // +5 = arbitrary value
double initialBaseVelocity = 1d;
double velocityLimit = 3d;
double movementToCenter = 0.01; // 1% towards center
List<Boid> boids;
static Random rnd = new Random();
double sceneWidth = 1024;
double sceneHeight = 768;
Pane playfield;
Rectangle rectangle;
#Override
public void start(Stage primaryStage) {
BorderPane root = new BorderPane();
playfield = new Pane();
playfield.setPrefSize(sceneWidth, sceneHeight);
Text infoText = new Text( "Drag the rectangle and have the flock follow it");
root.setTop(infoText);
root.setCenter(playfield);
Scene scene = new Scene(root, sceneWidth, sceneHeight, Color.WHITE);
//scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
// create boids
createBoids();
// add boids to scene
playfield.getChildren().addAll(boids);
double w = 20;
double h = 20;
rectangle = new Rectangle( w, h);
rectangle.relocate(sceneWidth / 2 - w/2, sceneHeight / 4 - h/2);
playfield.getChildren().add(rectangle);
MouseGestures mg = new MouseGestures();
mg.makeDraggable(rectangle);
// animation loop
AnimationTimer loop = new AnimationTimer() {
#Override
public void handle(long now) {
boids.forEach(Boid::move);
boids.forEach(Boid::updateUI);
}
};
loop.start();
}
private void createBoids() {
boids = new ArrayList<>();
// margin from top/left/bottom/right, so we have the boids initially more in the center
double marginX = sceneWidth / 4;
double marginY = sceneHeight / 4;
for (int i = 0; i < numBoids; i++) {
// random position around the center
double x = rnd.nextDouble() * (sceneWidth - marginX * 2) + marginX;
double y = rnd.nextDouble() * (sceneHeight - marginY * 2) + marginY;
// initial random velocity depending on speed
double v = Math.random() * 4 + initialBaseVelocity;
Boid boid = new Boid(i, x, y, v);
boids.add(boid);
}
}
// Rule 1: Boids try to fly towards the centre of mass of neighbouring boids.
public Point2D rule1(Boid boid) {
Point2D pcj = new Point2D(0, 0);
for( Boid neighbor: boids) {
if( boid == neighbor)
continue;
pcj = pcj.add( neighbor.position);
}
if( boids.size() > 1) {
double div = 1d / (boids.size() - 1);
pcj = pcj.multiply( div);
}
pcj = (pcj.subtract(boid.position)).multiply( movementToCenter);
return pcj;
}
// Rule 2: Boids try to keep a small distance away from other objects (including other boids).
public Point2D rule2(Boid boid) {
Point2D c = new Point2D(0, 0);
for( Boid neighbor: boids) {
if( boid == neighbor)
continue;
double distance = (neighbor.position.subtract(boid.position)).magnitude();
if( distance < boidMinDistance) {
c = c.subtract(neighbor.position.subtract(boid.position));
}
}
return c;
}
// Rule 3: Boids try to match velocity with near boids.
public Point2D rule3(Boid boid) {
Point2D pvj = new Point2D(0, 0);
for( Boid neighbor: boids) {
if( boid == neighbor)
continue;
pvj = pvj.add( neighbor.velocity);
}
if( boids.size() > 1) {
double div = 1d / (boids.size() - 1);
pvj = pvj.multiply( div);
}
pvj = (pvj.subtract(boid.velocity)).multiply(0.125); // 0.125 = 1/8
return pvj;
}
// tend towards the rectangle
public Point2D tendToPlace( Boid boid) {
Point2D place = new Point2D( rectangle.getBoundsInParent().getMinX() + rectangle.getBoundsInParent().getWidth() / 2, rectangle.getBoundsInParent().getMinY() + rectangle.getBoundsInParent().getHeight() / 2);
return (place.subtract(boid.position)).multiply( 0.01);
}
public class Boid extends Circle {
int id;
Point2D position;
Point2D velocity;
double v;
// random color
Color color = randomColor();
public Boid(int id, double x, double y, double v) {
this.id = id;
this.v = v;
position = new Point2D( x, y);
velocity = new Point2D( v, v);
setRadius( boidRadius);
setStroke(color);
setFill(color.deriveColor(1, 1, 1, 0.2));
}
public void move() {
Point2D v1 = rule1(this);
Point2D v2 = rule2(this);
Point2D v3 = rule3(this);
Point2D v4 = tendToPlace(this);
velocity = velocity
.add(v1)
.add(v2)
.add(v3)
.add(v4)
;
limitVelocity();
position = position.add(velocity);
constrainPosition();
}
private void limitVelocity() {
double vlim = velocityLimit;
if( velocity.magnitude() > vlim) {
velocity = (velocity.multiply(1d/velocity.magnitude())).multiply( vlim);
}
}
// limit position to screen dimensions
public void constrainPosition() {
double xMin = boidRadius;
double xMax = sceneWidth - boidRadius;
double yMin = boidRadius;
double yMax = sceneHeight - boidRadius;
double x = position.getX();
double y = position.getY();
double vx = velocity.getX();
double vy = velocity.getY();
if( x < xMin) {
x = xMin;
vx = v;
}
else if( x > xMax) {
x = xMax;
vx = -v;
}
if( y < yMin) {
y = yMin;
vy = v;
}
else if( y > yMax) {
y = yMax;
vy = -v;
}
// TODO: modification would be less performance consuming => find out how to modify the vector directly or create own Poin2D class
position = new Point2D( x, y);
velocity = new Point2D( vx, vy);
}
public void updateUI() {
setCenterX(position.getX());
setCenterY(position.getY());
}
}
public static Color randomColor() {
int range = 220;
return Color.rgb((int) (rnd.nextDouble() * range), (int) (rnd.nextDouble() * range), (int) (rnd.nextDouble() * range));
}
public static class MouseGestures {
class DragContext {
double x;
double y;
}
DragContext dragContext = new DragContext();
public void makeDraggable( Node node) {
node.setOnMousePressed( onMousePressedEventHandler);
node.setOnMouseDragged( onMouseDraggedEventHandler);
node.setOnMouseReleased( onMouseReleasedEventHandler);
}
EventHandler<MouseEvent> onMousePressedEventHandler = new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if( event.getSource() instanceof Circle) {
Circle circle = ((Circle) (event.getSource()));
dragContext.x = circle.getCenterX() - event.getSceneX();
dragContext.y = circle.getCenterY() - event.getSceneY();
} else {
Node node = ((Node) (event.getSource()));
dragContext.x = node.getTranslateX() - event.getSceneX();
dragContext.y = node.getTranslateY() - event.getSceneY();
}
}
};
EventHandler<MouseEvent> onMouseDraggedEventHandler = new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if( event.getSource() instanceof Circle) {
Circle circle = ((Circle) (event.getSource()));
circle.setCenterX( dragContext.x + event.getSceneX());
circle.setCenterY( dragContext.y + event.getSceneY());
} else {
Node node = ((Node) (event.getSource()));
node.setTranslateX( dragContext.x + event.getSceneX());
node.setTranslateY( dragContext.y + event.getSceneY());
}
}
};
EventHandler<MouseEvent> onMouseReleasedEventHandler = new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
}
};
}
public static void main(String[] args) {
launch(args);
}
}
A 3D version is just a matter of using Points3D instead of Points2D and Spheres and Boxes instead of Circles and Rectangles.
I also suggest you read the excellent book The Nature of Code by Daniel Shiffman, especially the chapter Autonomous Agents. It deals in detail with the Boids.
I'm building a Tree traversal program which allows users to run BFS and DFS traversals, as well as add and remove nodes.
So far I've been able to update the adjacency matrix when someone clicks to add a new child node to a parent:
Then I click Add Node, which adds Z to parent A:
You can see that the adjacency matrix appends Z to A... but I'm expecting the node Z to appear on the left side tree as well.
I think the problem is the updated nodeList is not being sent to paintComponent() loop for painting... so it's not being shown.
Here is a SSCCE of my program:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import javax.swing.JFrame;
public class MainSSCCE extends JFrame {
static MainSSCCE run;
int amount, nodeWidth, nodeHeight;
GraphSSCCE g;
JFrame f;
public MainSSCCE(){
f = new JFrame("DTurcotte's Graph Traversals");
g = new GraphSSCCE(450, 300);
f.add(g);
f.setSize(g.getWidth(),g.getHeight());
f.setVisible(true);
nodeWidth = 25;
nodeHeight = 25;
f.setResizable(false);
f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
public static void main(String[] args) {
run = new MainSSCCE();
}
}
Graph:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GraphSSCCE extends JPanel {
ArrayList<NodesSSCCE> nodeList;
public int[][] adjMatrix;
NodesSSCCE rootNode;
int size, height, width, x, y, counter;
Color color;
String message = "", run = "", nodeVal = "";
JButton AddButton;
JLabel label;
int nodeX = 180, nodeY = 100, nodeWidth, nodeHeight;
TextField child;
JComboBox parents;
public GraphSSCCE(int w, int h) {
height = h;
width = w;
nodeList = new ArrayList<NodesSSCCE>();
nodeWidth = 25;
nodeHeight = 25;
AddButton = new JButton("Add Node");
label = new JLabel("to parent");
label.setForeground(Color.WHITE);
child = new TextField(1);
parents = new JComboBox();
add(AddButton);
add(child);
add(label);
add(parents);
NodesSSCCE nA = new NodesSSCCE("A", nodeX, nodeY, nodeWidth, nodeHeight);
NodesSSCCE nB = new NodesSSCCE("B", nodeX, nodeY, nodeWidth, nodeHeight);
NodesSSCCE nC = new NodesSSCCE("C", nodeX, nodeY, nodeWidth, nodeHeight);
addNode(nA);
addNode(nB);
addNode(nC);
setRootNode(nA);
connectNode(nA, nB);
connectNode(nA, nC);
for (NodesSSCCE n : nodeList) {
parents.addItem(n.getValue());
}
//send in selected parent from combo box
AppendChildren ac = new AppendChildren(child);
this.child.addActionListener(ac);
this.AddButton.addActionListener(ac);
}
class AppendChildren implements ActionListener {
private TextField child;
public AppendChildren(TextField child) {
this.child = child;
}
public void actionPerformed(ActionEvent ae) {
String childName = child.getText();
NodesSSCCE newChild = new NodesSSCCE(childName, nodeX, nodeY, nodeWidth, nodeHeight);
appendNode(rootNode, newChild);
}
}
public int getHeight() {
return height;
}
public int getWidth() {
return width;
}
public void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(0, 0, width, height);
g.setColor(rootNode.getColor());
g.fillRect(rootNode.getX(), rootNode.getY(), rootNode.getWidth(), rootNode.getHeight());
g.setColor(Color.WHITE);
g.drawString(rootNode.getValue(), rootNode.getX()+9, rootNode.getY()+16);
paintComponent(g, rootNode);
}
public void paintComponent(Graphics g, NodesSSCCE parentNode) {
ArrayList<NodesSSCCE> nodePrintList = new ArrayList<NodesSSCCE>();
if (nodeList.indexOf(parentNode)==nodeList.size()) {
System.out.println("\nend");
}
else {
nodePrintList = getChildren(parentNode);
int x = parentNode.getX()-50;
//PAINT TREE: THIS IS NOT PAINTING THE NEWLY APPENDED NODE
for (NodesSSCCE child : nodePrintList) {
g.setColor(child.getColor());
child.setX(x);
child.setY(parentNode.getY()+50);
g.fillRect(child.getX(), child.getY(), child.getWidth(), child.getHeight());
g.setColor(Color.WHITE);
g.drawString(child.getValue(), child.getX()+9, child.getY()+16);
x+=50;
paintComponent(g, child);
g.setColor(child.getColor());
g.drawLine(parentNode.getX()+10, parentNode.getY()+23, child.getX()+10, child.getY());
}
//PAINT ADJACENCY MATRIX
for (int i = 0; i < adjMatrix.length; i++) {
for (int j = 0; j < adjMatrix[i].length; j++) {
g.setColor(Color.white);
g.drawString("" + adjMatrix[i][j], (i*19)+350, (j*19)+100);
g.setColor(Color.gray);
g.drawString("" + nodeList.get(i).getValue(), (i*19)+350, 75);
}
g.drawString("" + nodeList.get(i).getValue(), 325, (i*19)+100);
}
}
}
public void setRootNode(NodesSSCCE n) {
rootNode = n;
}
public NodesSSCCE getRootNode() {
return rootNode;
}
public void addNode(NodesSSCCE n) {
nodeList.add(n);
}
public void appendNode(NodesSSCCE parent, NodesSSCCE child) {
//add new node X to nodeList
addNode(child);
int newSize = nodeList.size();
//make a new adj matrix of the new size...
int[][] adjMatrixCopy = new int[newSize][newSize];
int fromNode = nodeList.indexOf(parent);
int toNode = nodeList.indexOf(child);
//copy adjMatrix data to new matrix...
for (int i = 0; i < adjMatrix.length; i++) {
for (int j = 0; j < adjMatrix[i].length; j++) {
adjMatrixCopy[i][j] = adjMatrix[i][j];
}
}
adjMatrixCopy[fromNode][toNode] = 1;
adjMatrix = adjMatrixCopy;
repaint();
}
public void connectNode(NodesSSCCE from, NodesSSCCE to)
{
if(adjMatrix == null) {
size = nodeList.size();
adjMatrix = new int[size][size];
}
int fromNode = nodeList.indexOf(from);
int toNode = nodeList.indexOf(to);
adjMatrix[fromNode][toNode] = 1;
}
public ArrayList<NodesSSCCE> getChildren (NodesSSCCE n) {
ArrayList<NodesSSCCE> childrenList;
childrenList = new ArrayList<NodesSSCCE>();
int index = nodeList.indexOf(n);
int col = 0;
while (col < size) {
if (adjMatrix[index][col] == 1) {
childrenList.add(nodeList.get(col));
}
col++;
}
return childrenList;
}
}
Nodes class:
import java.awt.Color;
import java.awt.Graphics;
public class NodesSSCCE {
Boolean visited;
String val;
Color color;
int xLoc, yLoc, width, height;
public NodesSSCCE(String s, int x, int y, int w, int h) {
visited = false;
val=s;
xLoc = x;
yLoc = y;
width = w;
height = h;
color = Color.gray;
}
public int getHeight() {
return height;
}
public int getWidth() {
return width;
}
public int getX() {
return xLoc;
}
public int getY() {
return yLoc;
}
public void setX(int x) {
xLoc = x;
}
public void setY(int y) {
yLoc = y;
}
public void visited(Boolean v) {
visited = v;
}
public String getValue() {
return val;
}
public void setValue(String value) {
val = value;
}
public void setColor (Color c) {
color = c;
}
public Color getColor () {
return color;
}
}
Nope, ignore my comment.
You forget to update size correctly.
In the GraphSSCCE, go to method getChildren(NodesSSCCE) and change the loop condition from col < size to col < nodeList.size().
Being able to debug your own programs can save a lot of time.