Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a circle move on events?

Tags:

javafx-2

I'm pretty new to javafx so I'm trying to learn here so please be reasonable and don't dis away my question, I really appreciate any help at all, thanks!

I would like to know how I could move an object, let's say this circle on different events, like keypress or mouseclick, mousemove, whatever.

Circle circle = new Circle();
circle.setCenterX(100.0f);
circle.setCenterY(100.0f);
circle.setRadius(50.0f);

Do I need to use that KeyFrame thing I saw on the javafx site tutorial, or how does this work?

I would not have asked this here if I weren't feeling so lost, honestly. So to make this clear: What is the code for moving objects that I created, by using events?

EDIT: By moving it I mean, press up key and it moves up by a few pixels, transform it maybe, with another key, or click somewhere on the scene and make it move there instantly or travel there with a certain speed. I don't have to redraw it like you need to with html5 canvas, I hope, right?

like image 504
Andrei Cristian Prodan Avatar asked Dec 04 '22 00:12

Andrei Cristian Prodan


1 Answers

I don't have to redraw it like you need to with html5 canvas, I hope, right?

Not if you are using a standard JavaFX scene graph as opposed to a JavaFX canvas.

I would like to know how I could move an object, let's say this circle on different events, like keypress or mouseclick, mousemove, whatever

There are three ways to move a Shape:

  1. You can adjust the shape's geometry (e.g. the centerX/centerY properties of a circle).
  2. You can adjust the shape's layout (e.g. it's layoutX/layoutY properties).
  3. You can adjust the shape's translation (e.g. it's translateX/translateY properties).

You can think of the layout as the home position for the object; i.e. where it should normally be in the context of it's parent group. You can think of it's translation transform as a temporary position for an object (often used when the object is being animated).

If you are using a layout pane such as a VBox or TilePane, then the layout pane will handle setting the layout co-ordinates of the child node for you. If you are using a simple Group or a plain Pane or Region, then you are responsible for setting the correct layout values for the child nodes.

To listen for events, set event handlers on Nodes or Scenes.

Here is a small sample app which demonstrates the above. It places the object to be moved inside a Group and modifies the position of the object within a Group in response to various events.

movementevents

like image 90
jewelsea Avatar answered Jan 17 '23 08:01

jewelsea