Jump to content
New Reality: Ads For Members ×

cannot understand javafx and object oriented code structuring


Recommended Posts

package RandomWalk;

import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;


//==========================================================================================
//A class that uses JavaFX must extend javafx.application.Application
//==========================================================================================
public class JavafxRandomWalk extends Application
{
    private static final int DRAW_WIDTH  = 600;
    private static final int DRAW_HEIGHT = 600;
    private static final double NANO = 0.000000001;

    private Animation myAnimation;  //Reference to an inner class that gets called at 60Hz
    private Canvas canvas;          //Area on which to draw graphics items.
    private GraphicsContext gtx;    //Drawing methods for the Canvas.
    private int x=DRAW_WIDTH/2;
    private int y=DRAW_HEIGHT/2;
    private int frameNumber = 0;
    private int distance = 1;
    private double timeOfLastDraw = 0;

    @Override
    //=========================================================================
    //start(Stage stage)
    //This is a JavaFX callback method. It is called by JavaFX after JavaFX
    //   has created a window. The parameter, Stage stage, is a pointer to
    //   the part of the window where the programmer can add widgets, such as
    //   buttons, menus and canvases.
    //=========================================================================
    public void start(Stage stage) throws Exception
    {
        //Set the window's title in its title bar.
        stage.setTitle("Random Walk");


        //A Canvas is an area that supports graphics drawing
        //To get this to work, there is a hierarchy of objects that is needed:
        //   1) The canvas is placed in a new instance of VBox.
        //   2) The instance of VBox is placed in a new instance of Scene.
        //   3) The instance of Scene is placed in the given instance of Stage.
        canvas = new Canvas(DRAW_WIDTH, DRAW_HEIGHT);

        //A GraphicsContext, gtx, is a pointer to a set of drawing tools
        //   that can be performed on an instance of a Canvas, canvas.
        gtx = canvas.getGraphicsContext2D();

        //All lines drawn after this setLineWidth(3) is called will have a
        //  width of 3 pixels. This effect lines drawn until changed by another
        //  call to setLineWidth(int width).
        gtx.setLineWidth(1);

        gtx.setFill(Color.DEEPSKYBLUE);
        //gtx.fillRect(left, top, width, height) will fill an axis-aligned rectangular
        //    area with the current fill color. The rectangle is defined by the 4
        //   parameters:
        //         left  (x-coordinate in pixels of the left corner of the rectangle).
        //         top   (y-coordinate in pixels of the top corner of the rectangle).
        //         width (width in pixels of the rectangle).
        //         height (height in pixels of the rectangle).
        gtx.fillRect(0, 0, DRAW_WIDTH, DRAW_HEIGHT);



        VBox vBox = new VBox();
        vBox.getChildren().addAll(canvas);

        Scene scene = new Scene(vBox, DRAW_WIDTH, DRAW_HEIGHT);

        stage.setScene(scene);
        stage.show();

        //At this point, the an empty, white window is created.

        //Now, we create an new AnimationTimer and start it running.
        //  this will tell JavaFX to call the AnimationTimer's handle method
        //  at a rate of 60 times per second.
        //Each time the handle method is called, a new image can be drawn.
        //Each new image is called a "frame". Thus, this will **attempt** to
        //  draw at 60 frames per second (fps).
        myAnimation = new Animation();

        myAnimation.start();
    }


    //===========================================================================================
    // Animation is an inner class of our JavafxRandomBox class.
    // Animation is an "inner class" because it is inside the JavafxRandomBox class.
    // Since Animation extends AnimationTimer, the Animation class MUST implement
    //   public void handle(long now), a callback method that is called by JavaFX at 60Hz.
    //===========================================================================================
    class Animation extends AnimationTimer
    {
        @Override
        //=========================================================================================
        //handel is a callback method called by JavaFX at 60Hz.
        //    now - The timestamp of the current frame given in nanoseconds.
        // This number is not useful by itself, but when subtracted to from another saved now
        //    gives the difference in nanoseconds between the two times.
        //=========================================================================================
        public void handle(long now)
        {

            double currentTimeInSec = now*NANO;
            if (currentTimeInSec - timeOfLastDraw < 0.005) return;

            timeOfLastDraw = currentTimeInSec;

            gtx.setLineWidth(1);
            gtx.setStroke(Color.BLACK);

            int x2 = x;
            int y2 = y;
            double r = Math.random(); // [0, 1)
            if (r < 0.25)
            {
                x2 = x + distance;
            }
            else if (r < 0.5)
            {
                y2 = y - distance;
            }
            else if (r < 0.75)
            {
                x2 = x - distance;
            }
            else
            {
                y2 = y + distance;
            }

            gtx.strokeLine(x,y, x2, y2);

            x = x2;
            y = y2;
            frameNumber++;



        }
    } //This bracket ends Animation, the inner class.


    //===========================================================================================
    // Every Java program must have public static void main(String[] args).
    // In a JavaFX program, main starts JavaFX by calling:
    //     javafx.application.Application.launch(String[] args)
    //===========================================================================================
    public static void main(String[] args)
    {
        launch(args);
    }
}

This code simulates self avoiding random walk in java. My concern is not the logic of the program, but the structure of the program. And the javafx way of displaying stuffs on screen. It just does not come to me instantly or lately

Honestly, the comments give a good overview of the whole thing. Did you have any specific questions about what they said?

 

7 hours ago, polaryeti said:

My concern is not the logic of the program, but the structure of the program.

There's a big class containing all the code, an inner class that handles just the animation portion, and a static main.
The big class's start() initializes things and then tells JavaFX to start executing the animation.
The animation happens by executing handle() at ~60 calls/second (aka Hz).

7 hours ago, polaryeti said:

And the javafx way of displaying stuffs on screen. It just does not come to me instantly or lately

The code for handle, which is the only method in that class, calculates a couple X,Y coordinates and draws then a line on the canvas...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.