How can I bind a three doubleProperty Red, Green and Blue to a 'circle.fillProperty()' in JavaFX?
I can easily bind for example the radiusProperty of a circle to a doubleProperty like this:
Circle circle = new Circle();
circle.radiusProperty().bind(boid.getRadiusProperty());
You can use Bindings.createObjectBinding.
The fillProperty of the Circle has the type of ObjectProperty<Paint> so you have to create a Paint object in the binding:
private IntegerProperty r = new SimpleIntegerProperty(0);
private IntegerProperty g = new SimpleIntegerProperty(0);
private IntegerProperty b = new SimpleIntegerProperty(0);
circle.fillProperty().bind(Bindings.createObjectBinding(() -> Color.rgb(r.get(), g.get(), b.get()), r, g, b));
Here is a complete example:
This example uses Spinners as input control, note that the valueProperty of these controls could be directly used as dependency of the binding.
public class Main extends Application {
private IntegerProperty r = new SimpleIntegerProperty(0);
private IntegerProperty g = new SimpleIntegerProperty(0);
private IntegerProperty b = new SimpleIntegerProperty(0);
#Override
public void start(Stage primaryStage) {
try {
BorderPane root = new BorderPane();
Scene scene = new Scene(root, 400, 400);
Group group = new Group();
Circle circle = new Circle(60);
circle.setCenterX(70);
circle.setCenterY(70);
circle.fillProperty()
.bind(Bindings.createObjectBinding(() -> Color.rgb(r.get(), g.get(), b.get()), r, g, b));
group.getChildren().add(circle);
root.setCenter(group);
Spinner<Integer> spinnerR = new Spinner<>(0, 255, 100);
Spinner<Integer> spinnerG = new Spinner<>(0, 255, 100);
Spinner<Integer> spinnerB = new Spinner<>(0, 255, 100);
r.bind(spinnerR.valueProperty());
g.bind(spinnerG.valueProperty());
b.bind(spinnerB.valueProperty());
root.setBottom(new HBox(spinnerR, spinnerG, spinnerB));
primaryStage.setScene(scene);
primaryStage.show();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
Note: It is the same with DoubleProperty.
private DoubleProperty r = new SimpleDoubleProperty(0);
private DoubleProperty g = new SimpleDoubleProperty(0);
private DoubleProperty b = new SimpleDoubleProperty(0);
circle.fillProperty().bind(Bindings.createObjectBinding(() -> Color.rgb(r.getValue().intValue(), g.getValue().intValue(), b.getValue().intValue()), r, g, b));
You can do
DoubleProperty red = new SimpleDoubleProperty();
red.bind(Bindings.createDoubleBinding( () ->
((Color)circle.getFill()).getRed(),
circle.fillProperty()));
and similarly for green and blue.
Related
I have an object, like a box in this example.
I want this box to move in a sine to the left on the sphere when the Z-axis is rotated. But after the box has made a curve, i.e. the rotation of the Z-axis is back to 0. The sphere no longer rotates downwards as it did at the start, but upwards to the right.
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;
import javafx.scene.shape.Box;
import javafx.scene.shape.Sphere;
import javafx.scene.transform.*;
import javafx.stage.Stage;
import org.joml.Matrix4f;
import org.joml.Quaternionf;
import java.util.ArrayList;
public class TestFX extends Application {
public static final float WIDTH = 1400;
public static final float HEIGHT = 1000;
private final ArrayList<String> input = new ArrayList<>();
private final Sphere sphere = new Sphere(500);
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
Flugzeug flieger = new Flugzeug(30, 30, 50);
flieger.setMaterial(new PhongMaterial(Color.GREEN));
flieger.setTranslateZ(330);
flieger.getTransforms().add(new Rotate(20, Rotate.X_AXIS));
sphere.translateZProperty().set(710);
sphere.translateYProperty().set(420);
PhongMaterial phongMaterial = new PhongMaterial();
phongMaterial.setDiffuseMap(new Image(getClass().getResourceAsStream("Earth_diffuse_8k.png")));
sphere.setMaterial(phongMaterial);
PerspectiveCamera camera = new PerspectiveCamera(true);
camera.setFarClip(40000);
Group root = new Group(flieger, sphere);
Scene scene = new Scene(root, WIDTH, HEIGHT, true);
scene.setCamera(camera);
primaryStage.setTitle("FliegenFX");
primaryStage.setScene(scene);
primaryStage.show();
new AnimationTimer() {
#Override
public void handle(long now) {
initGameLogic(flieger);
dreheErde(flieger, sphere);
}
}.start();
scene.setOnKeyPressed(event -> {
String code = event.getCode().toString();
if (!input.contains(code))
input.add(code);
});
scene.setOnKeyReleased(event -> {
String code = event.getCode().toString();
input.remove(code);
});
}
// TODO Erddrehung nach Drehung beibehalten
private void dreheErde(Flugzeug flieger, Sphere erde) {
double rotationFactor = 0.005;
double drehung = flieger.getDrehung() * rotationFactor;
double amplitude = 2;
double frequency = 0.001;
float angle = (float) (Math.sin(drehung * frequency) * amplitude);
Quaternionf quat = new Quaternionf();
Matrix4f matrix4f = new Matrix4f();
Affine affine = new Affine();
quat.rotateY(angle);
quat.rotateZ(angle);
quat.rotateX(-0.001f);
quat.normalize();
quat.get(matrix4f);
float[] matrixArray = new float[16];
matrix4f.get(matrixArray);
double[] matrix = new double[16];
for (int i = 0 ; i < matrixArray.length; i++)
{
matrix[i] = matrixArray[i];
}
affine.append(matrix, MatrixType.MT_3D_4x4, 0);
erde.getTransforms().add(affine);
}
private void initGameLogic(Flugzeug flieger) {
if (input.contains("LEFT")) {
flieger.rotateByZ(-0.5);
}
if (input.contains("RIGHT")) {
flieger.rotateByZ(0.5);
}
}
private class Flugzeug extends Box{
private double drehung = 0;
private Rotate r;
private Transform t = new Rotate();
public Flugzeug(double width, double height, double depth){
super(width, height, depth);
}
public void rotateByZ(double ang){
drehung += ang;
r = new Rotate(ang, Rotate.Z_AXIS);
t = t.createConcatenation(r);
getTransforms().clear();
getTransforms().addAll(t);
}
public double getDrehung() {
return drehung;
}
}
}
I have tried many different ways with trigonometry but they have not been successful. This was for example to move the X-axis of the sphere also according to the sine or to subtract the movements of the Y and Z axis of the sphere as cosine.
I think it has to be transformed in a Rotation Matrix, but i‘ve never had matrix calculation.
Rotating a Group inside another Group in 3d scene
In this approach Box instance doesn't seem to move 'cause it's moving with the camera . Camera and box are moving together because is it's Group parent who is rotating with keyboard event . The Sphere node is in another group and is not affected . Sphere itself is rotating in Y axis
App.java
public class App extends Application {
#Override
public void start(Stage stage) {
Shape3D sphere = new Sphere(10);
PhongMaterial mat = new PhongMaterial();
mat.setDiffuseMap(new Image("https://www.h-schmidt.net/map/map.jpg"));
sphere.setMaterial(mat);
RotateTransition sphereRotation = new RotateTransition(Duration.seconds(40), sphere);
sphereRotation.setAxis(Rotate.Y_AXIS);
sphereRotation.setToAngle(360);
sphereRotation.setInterpolator(Interpolator.LINEAR);
sphereRotation.setCycleCount(Animation.INDEFINITE);
sphereRotation.play();
Shape3D box = new Box(2, 2, 2);
box.setMaterial(new PhongMaterial(Color.ORANGE));
box.setTranslateZ(-11);
PerspectiveCamera camera = new PerspectiveCamera(true);
camera.setTranslateZ(-30);
var planeGroup = new Group(box, camera);
Group sphereGroup = new Group(sphere);
Group group3d = new Group(planeGroup, sphereGroup);
Scene scene = new Scene(group3d, 640, 480, true, SceneAntialiasing.BALANCED);
scene.setOnKeyPressed((t) -> {
if (t.getCode() == KeyCode.UP) {
Rotate r = new Rotate(-2);
r.setAxis(Rotate.X_AXIS);
planeGroup.getTransforms().add(r);
}
if (t.getCode() == KeyCode.LEFT) {
Rotate r = new Rotate(2);
r.setAxis(Rotate.Y_AXIS);
planeGroup.getTransforms().add(r);
}
if (t.getCode() == KeyCode.RIGHT) {
Rotate r = new Rotate(-2);
r.setAxis(Rotate.Y_AXIS);
planeGroup.getTransforms().add(r);
}
if (t.getCode() == KeyCode.DOWN) {
Rotate r = new Rotate(2);
r.setAxis(Rotate.X_AXIS);
planeGroup.getTransforms().add(r);
}
});
scene.setCamera(camera);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
I want to make a program in javafx in which when a button is pressed rectangle or circle is created with random dimension and color. I have written code but facing some problem. In it when I'm clicking button, figure is appearing but when i click it again figure stays same. After 3-4 clicks figure is changing.
import javafx.application.*;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.canvas.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.paint.*;
import javafx.scene.shape.*;
import javafx.scene.text.*;
import javafx.scene.image.*;
import javafx.collections.*;
import javafx.geometry.*;
import javafx.event.*;
import java.util.*;
public class ranshap extends Application
{
double x1,y1,x2,y2;
Rectangle rectangle;
Circle circle;
Color rectangleColor;
Color circleColor;
Button b;
Pane pane;
Scene scene;
Stage stage;
public void start (Stage stage)
{
stage.setTitle("Drawing Rectangle and Circle");
CreateRect c= new CreateRect();
b= new Button("Click me");
b.setOnAction(c);
rectangle = new Rectangle();
circle = new Circle();
/*rectangle.setX(50);
rectangle.setY(50);
rectangle.setWidth(200);
rectangle.setHeight(50);
rectangleColor= new Color(0.0,0.8,0.2,0.6);
rectangle.setFill(rectangleColor);*/
pane= new Pane();
pane.getChildren().add(b);
scene= new Scene(pane,500,300);
stage.setScene(scene);
stage.show();
}
private class CreateRect implements EventHandler <ActionEvent>
{
public void handle(ActionEvent e)
{
double width,height,r,g,b,o,s,radius;
Random generator= new Random();
s=generator.nextDouble();
if(s>0.5)
{
pane.getChildren().remove(circle);
pane.getChildren().add(rectangle);
width= generator.nextDouble()*100;
height= generator.nextDouble()*100;
r= generator.nextDouble();
g= generator.nextDouble();
b= generator.nextDouble();
o= generator.nextDouble();
rectangle.setX(50);
rectangle.setY(50);
rectangle.setWidth(width);
rectangle.setHeight(height);
rectangleColor= new Color(r,g,b,o);
rectangle.setFill(rectangleColor);
}
else
{
pane.getChildren().remove(rectangle);
pane.getChildren().add(circle);
radius=generator.nextDouble()*100;
circle.setCenterX (100);
circle.setCenterY (100);
circle.setRadius (radius);
r= generator.nextDouble();
g= generator.nextDouble();
b= generator.nextDouble();
o= generator.nextDouble();
circleColor= new Color(r,g,b,o);
circle.setFill(circleColor);
}
}
}
}
Actrully, you add the same children twice. Using the following code
public class ranshap extends Application {
double x1, y1, x2, y2;
Rectangle rectangle;
Circle circle;
Color rectangleColor;
Color circleColor;
Button b;
Pane pane;
Scene scene;
Stage stage;
#Override
public void start(Stage stage) {
stage.setTitle("Drawing Rectangle and Circle");
CreateRect c = new CreateRect();
b = new Button("Click me");
b.setOnAction(c);
rectangle = new Rectangle();
circle = new Circle();
/*
* rectangle.setX(50); rectangle.setY(50); rectangle.setWidth(200); rectangle.setHeight(50); rectangleColor= new
* Color(0.0,0.8,0.2,0.6); rectangle.setFill(rectangleColor);
*/
pane = new Pane();
pane.getChildren().add(b);
scene = new Scene(pane, 500, 300);
stage.setScene(scene);
stage.show();
}
private class CreateRect implements EventHandler<ActionEvent> {
#Override
public void handle(ActionEvent e) {
double width, height, r, g, b, o, s, radius;
Random generator = new Random();
s = generator.nextDouble();
pane.getChildren().remove(rectangle);
pane.getChildren().remove(circle);
if (s > 0.5) {
pane.getChildren().add(rectangle);
width = generator.nextDouble() * 100;
height = generator.nextDouble() * 100;
r = generator.nextDouble();
g = generator.nextDouble();
b = generator.nextDouble();
o = generator.nextDouble();
rectangle.setX(50);
rectangle.setY(50);
rectangle.setWidth(width);
rectangle.setHeight(height);
rectangleColor = new Color(r, g, b, o);
rectangle.setFill(rectangleColor);
} else {
pane.getChildren().add(circle);
radius = generator.nextDouble() * 100;
circle.setCenterX(100);
circle.setCenterY(100);
circle.setRadius(radius);
r = generator.nextDouble();
g = generator.nextDouble();
b = generator.nextDouble();
o = generator.nextDouble();
circleColor = new Color(r, g, b, o);
circle.setFill(circleColor);
}
}
}
public static void main(String[] args) {
launch(args);
}
}
My JavaFX slider does not change value when I'm trying to move.
My slider is inside a GridPane layout.
My code looks like this, if you need more just ask :
root = new GridPane();
root.setLayoutY(canvasHeight);
root.setGridLinesVisible(true);
root.setPadding(new Insets(10, 10, 10, 10));
root.setVgap(2);
Label lblAmount = new Label("Amount of fireworks : ");
GridPane.setConstraints(lblAmount, 0, 0);
root.getChildren().add(lblAmount);
Slider sliAmount = new Slider();
sliAmount.setMin(1);
sliAmount.setMax(10);
sliAmount.setValue(5);
sliAmount.setMaxWidth(100);
root.getChildren().add(sliAmount);
GridPane.setConstraints(sliAmount, 1, 0);
Label lblPSize = new Label("Size of particles : ");
GridPane.setConstraints(lblPSize, 0, 1);
root.getChildren().add(lblPSize);
root.getRowConstraints().add(new RowConstraints(15));
root.getColumnConstraints().add(new ColumnConstraints(140));
Here's a GIF to better understand what the problem is
Here's what it looks like in my small program :
EDIT : More code
Since my program is very small and has pretty much only the slider implemented here is all my code.
Main class
public class Main extends Application {
private final int CANVAS_WIDTH = 1600;
private final int CANVAS_HEIGHT = 750;
private final int MENU_HEIGHT = 150;
private GraphicsContext graphics;
private GUI gui;
#Override
public void start(Stage primaryStage) throws Exception{
gui = new GUI(CANVAS_WIDTH, CANVAS_HEIGHT, MENU_HEIGHT);
gui.setup();
Canvas canvas = new Canvas(CANVAS_WIDTH, CANVAS_HEIGHT);
graphics = canvas.getGraphicsContext2D();
clearCanvas();
gui.getRoot().getChildren().add(canvas);
primaryStage.setTitle("FireworkSim by Cedric Martens");
primaryStage.setScene(new Scene(gui.getRoot(), CANVAS_WIDTH, CANVAS_HEIGHT + MENU_HEIGHT, Color.rgb(137, 182, 255)));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
private void clearCanvas()
{
//graphics.setFill(Color.BLACK);
//graphics.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
}
}
GUI class
public class GUI {
private GridPane root;
private int canvasWidth;
private int canvasHeight;
private int menuHeight;
public GUI(int canvasWidth, int canvasHeight, int menuHeight)
{
this.canvasWidth = canvasWidth;
this.canvasHeight = canvasHeight;
this.menuHeight = menuHeight;
}
public void setup()
{
root = new GridPane();
root.setLayoutY(canvasHeight);
root.setGridLinesVisible(true);
root.setPadding(new Insets(10, 10, 10, 10));
root.setVgap(2);
Label lblAmount = new Label("Amount of fireworks : ");
GridPane.setConstraints(lblAmount, 0, 0);
root.getChildren().add(lblAmount);
Slider sliAmount = new Slider();
sliAmount.setMin(1);
sliAmount.setMax(10);
sliAmount.setValue(5);
sliAmount.setMaxWidth(100);
root.getChildren().add(sliAmount);
GridPane.setConstraints(sliAmount, 1, 0);
Label lblPSize = new Label("Size of particles : ");
GridPane.setConstraints(lblPSize, 0, 1);
root.getChildren().add(lblPSize);
root.getRowConstraints().add(new RowConstraints(15));
root.getColumnConstraints().add(new ColumnConstraints(140));
}
public GridPane getRoot() {
return root;
}
}
You're placing the canvas directly in the grid pane created by the GUI class, without specifying any layout properties (row and column indexes, for example). So the canvas is directly overlaying the grid pane, and receives the mouse events, preventing the slider from receiving them. Instead, use a layout pane that lays things out appropriately. For example:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class Main extends Application {
private final int CANVAS_WIDTH = 1600;
private final int CANVAS_HEIGHT = 750;
private final int MENU_HEIGHT = 150;
private GraphicsContext graphics;
private GUI gui;
#Override
public void start(Stage primaryStage) throws Exception{
BorderPane root = new BorderPane();
gui = new GUI(CANVAS_WIDTH, CANVAS_HEIGHT, MENU_HEIGHT);
gui.setup();
Canvas canvas = new Canvas(CANVAS_WIDTH, CANVAS_HEIGHT);
graphics = canvas.getGraphicsContext2D();
clearCanvas();
root.setCenter(canvas);
root.setBottom(gui.getRoot());
primaryStage.setTitle("FireworkSim by Cedric Martens");
primaryStage.setScene(new Scene(root, CANVAS_WIDTH, CANVAS_HEIGHT + MENU_HEIGHT, Color.rgb(137, 182, 255)));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
private void clearCanvas()
{
graphics.setFill(Color.BLACK);
graphics.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
}
}
I want to create an application with a button and a colour picker on the top and a canvas in the centre of a BorderPane. I created a main Class TestSceneBuilder and 2 listeners: one for the button and one for the ColorPicker. The question is: when I detect change in colour how do I pass it to my CerchioListener ?
Main Class:
public class TestSceneBuilder extends Application {
final int H = 300, W = 300; //height and width
BorderPane root;
#Override
public void start(Stage primaryStage) {
root = this.setScene();
Scene scene = new Scene(root, H, W);
primaryStage.setTitle("Test");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* This method is supposed to build the scene with all components:
* a button "Draw" that draws the rectangle
* a canvas
* a colorPicker
* #return
*/
BorderPane setScene(){
BorderPane border = new BorderPane();
final ColorPicker cp = new ColorPicker(Color.AQUA);
Canvas canvas = new Canvas(H, W);
Button btn = new Button("Draw");
/*CerchioListner should get the mouse clicked event and draw the circle*/
final CerchioListner l = new CerchioListner(canvas, cp.getValue());
btn.addEventHandler(MouseEvent.MOUSE_CLICKED, l);
/*ColorListener intercept the color change in ColorPicker cp and change the color of the
shape drawn*/
ColorListener cl = new ColorListener(cp);
cp.setOnAction(cl);
HBox hb = new HBox();
hb.getChildren().addAll(btn, cp);
border.setTop(hb);
BorderPane.setAlignment(hb, Pos.CENTER);
border.setCenter(canvas);
return border;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
Button listener: CerchioListener
public class CerchioListner implements javafx.event.EventHandler{
Canvas canvas = null;
Color colore;
public CerchioListner(Canvas c, Color colore) {
this.canvas = c;
this.colore = colore;
}
public void changeColor(Color c) {
this.colore = c;
}
#Override
public void handle(Event t) {
disegna();
}
public void disegna(){
canvas.getGraphicsContext2D().setFill(colore);
canvas.getGraphicsContext2D().fillOval(20, 20, 20, 20);
}
}
Color Picker listener: ColorListener
public class ColorListener implements javafx.event.EventHandler{
ColorPicker cp = null;
public ColorListener(ColorPicker cp) {
this.cp = cp;
}
#Override
public void handle(Event t) {
Color c = cp.getValue();
System.out.println("handle CP "+cp.getValue());
//restituisciColoreSelezionato(c);
}
/*public Color restituisciColoreSelezionato(Color c){
return c;
}*/
}
There are several things that is not the best you can have:
You have a Canvas, which is not member of Main, just a local variable in setScene(), therefore it is only accessible in that method. As the Canvas is the most important part of your class, you should have it as a class member because you want to access it anywhere from the class.
The listener for the Button should not store any reference to the selected color and to the Canvas, it is stored by Main and the listener should use that member.
The listener of the ColorPicker should not store any reference to the ColorPicker itself. The ColorPicker should be a member to make it able to access the currently selected color anywhere in Main.
I have updated your code to include these modifications:
public class TestSceneBuilder extends Application {
final int H = 300, W = 300;
BorderPane root;
Canvas canvas;
ColorPicker cp;
Button btn;
#Override
public void start(Stage primaryStage) {
root = this.setScene();
Scene scene = new Scene(root, H, W);
primaryStage.setTitle("Test");
primaryStage.setScene(scene);
primaryStage.show();
}
BorderPane setScene(){
BorderPane border = new BorderPane();
cp = new ColorPicker(Color.AQUA);
canvas = new Canvas(H, W);
btn = new Button("Draw");
btn.setOnAction((event) -> {
canvas.getGraphicsContext2D().setFill(cp.getValue());
canvas.getGraphicsContext2D().fillOval(20, 20, 20, 20);
});
HBox hb = new HBox();
hb.getChildren().addAll(btn, cp);
border.setTop(hb);
BorderPane.setAlignment(hb, Pos.CENTER);
border.setCenter(canvas);
return border;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
If you want to stay with external listeners:
Exchange this:
btn.setOnAction((event) -> {
canvas.getGraphicsContext2D().setFill(cp.getValue());
canvas.getGraphicsContext2D().fillOval(20, 20, 20, 20);
});
with
CerchioListener cerchioListener = new CerchioListener(canvas);
btn.setOnAction(cerchioListener);
cerchioListener.colorProperty.bind(cp.valueProperty());
and add the listener:
CerchioListener.java
public class CerchioListener implements EventHandler<ActionEvent> {
private Canvas canvas = null;
public ObjectProperty<Color> colorProperty = new SimpleObjectProperty<Color>(Color.WHITE);
public CerchioListener(Canvas c) {
this.canvas = c;
}
public Canvas getCanvas() {
return canvas;
}
public void setCanvas(Canvas canvas) {
this.canvas = canvas;
}
#Override
public void handle(ActionEvent t) {
canvas.getGraphicsContext2D().setFill(colorProperty.get());
canvas.getGraphicsContext2D().fillOval(20, 20, 20, 20);
}
}
I am quite beginner in Java and need some help with my application.
I am would like to use drag and drop on custom made shapes with javafx canvas i.e multiple polygons that make up a bow tie.
I have created a method that draws a bow tie that looks like this:
public void joonistaBowTie(GraphicsContext gc) {
// Bowtie left side
gc.setFill(Color.RED);
double xpoints[] = { 242, 242, 200 };
double ypoints[] = { 245, 290, 270 };
int num = 3;
gc.fillPolygon(xpoints, ypoints, num);
// Bowtie right side
gc.setFill(Color.RED);
double xpoints1[] = { 160, 160, 200 };
double ypoints1[] = { 245, 290, 270 };
int num1 = 3;
gc.fillPolygon(xpoints1, ypoints1, num1);
// Bowtie middle part
gc.setFill(Color.RED);
gc.fillOval(190, 255, 20, 30);
}
I have moved that method into a separate class called BowTie.
I also have a main class that looks like this:
public class GraafikaNaide extends Application {
Bowtie bowtie;
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("JavaFX-iga joonistatud kloun");
Group root = new Group();
Canvas canvas = new Canvas(1000, 1000);
GraphicsContext gc = canvas.getGraphicsContext2D();
joonista(gc);
root.getChildren().add(canvas);
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
private void joonista(GraphicsContext gc) {
Bowtie bowtie = new Bowtie();
bowtie.joonistaBowTie(gc);
}
I also found somewhat example on how to do drag and drop, but i just lack knowledge on how to implement this code to mine.
Could someone please help me with this?
Thanks
Using the link you provided, here is how you would incorporate it with your work:
public class GraafikaNaide extends Application
{
joonistaBowTie bowtie;
double orgSceneX, orgSceneY;
double orgTranslateX, orgTranslateY;
#Override
public void start(Stage primaryStage)
{
Canvas canvas = new Canvas(1000, 1000);
GraphicsContext gc = canvas.getGraphicsContext2D();
joonista(gc);
canvas.setOnMousePressed(canvasOnMousePressedEventHandler);
canvas.setOnMouseDragged(canvasOnMouseDraggedEventHandler);
Group root = new Group();
root.getChildren().add(canvas);
primaryStage.setTitle("JavaFX-iga joonistatud kloun");
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
private void joonista(GraphicsContext gc)
{
joonistaBowTie bowtie = new joonistaBowTie();
bowtie.joinBowTie(gc);
}
EventHandler<MouseEvent> canvasOnMousePressedEventHandler = new EventHandler<MouseEvent>()
{
#Override
public void handle(MouseEvent mouseEvent)
{
orgSceneX = mouseEvent.getSceneX();
orgSceneY = mouseEvent.getSceneY();
orgTranslateX = ((Canvas)(mouseEvent.getSource())).getTranslateX();
orgTranslateY = ((Canvas) (mouseEvent.getSource())).getTranslateY();
}
};
EventHandler<MouseEvent> canvasOnMouseDraggedEventHandler = new EventHandler<MouseEvent>()
{
#Override
public void handle(MouseEvent mouseEvent)
{
double offsetX = mouseEvent.getSceneX() - orgSceneX;
double offsetY = mouseEvent.getSceneY() - orgSceneY;
double newTranslateX = orgTranslateX + offsetX;
double newTranslateY = orgTranslateY + offsetY;
((Canvas) (mouseEvent.getSource())).setTranslateX(newTranslateX); //transform the object
((Canvas) (mouseEvent.getSource())).setTranslateY(newTranslateY);
}
};
}
Hope this helps.