Updated March 31, 2023
Introduction to JavaFX Game
JavaFX Game is more reliable, fast and light weight standalone application than Swing, Applet and AWT. Games can be done by animation packages in JavaFX. JavaFX provides rich GUI for gaming applications. JavaFX also provides beautiful graphics, this graphics are providing in JavaFX by using Canvas. Most of the JavaFX games has time based games so we can add time related operations with AnimationTimer class. Evenhandling the game user actions we have EventHandler class that is useful. This events are either keyboard or mouse events. Applying CSS styles in JavaFX application FXML (EFF-ectseXtended Markup Language) is required.
Prerequisites
- JDK installation.
- Understanding basic Java Code.
- Better understanding of JavaFX animation.
- CSS styles FXML knowledge required.
Frequently Used Constructors
Given below are frequently used constructors:
- Canvas(Width, Height): It creates Canvas instance by new keyword with 2 constructor arguments.
- AnimatedImage(): It creates AnimatedImage instance by new keyword without any constructor.
Frequently Used Methods
Given below are the frequently used methods:
- show(): The show() method is used for displaying output window.
- add(): The add() method is used for adding JavaFX element.
- remove(): The remove() method is used for adding JavaFX element.
- getGraphicsContext2D(): The getGraphicsContext2D() method is used for get the 2d graphics context.
- setFill( Color.RED ): The setFill() method is used to set the color.
- setLineWidth(int width): The setLineWidth() method is used to set the width.
- drawImage(): The drawImage() method is used to draw any image to the JavaFX element.
- setCenter(): The setCenter() method is used to set the element in the center.
- font(): The font() method is used to set the font.
- setPosition(): The setPosition() method is used to set the position.
- addVelocity(): The addVelocity() method is used to add the velocity to the JavaFX element.
How does Game work in JavaFX?
- Accessing JavaFX features user defined class must extendsApplication class.
- In JavaFX creating any JavaFX element is first step. ImageView, AnchorePane, ScrollPane, MenuBar etc. This can instantiate by using new keyword.
Syntax:
ImageViewimageView=new ImageView();
ScrollPanescrollPane=new ScrollPane();
AnchorPaneanchorPaneRef=new AnchorPane ();
.
.
Etc.
- Create Canvas is 2nd
Syntax:
Canvas canvasRef=new Canvas(width, height);
- Create VBox or any other display(like TilePane or HBox as per requirement) class to add the items is third step.
Syntax:
VBoxvBox=new VBox (); //Gives vertical box
vBox.getChildern().add(imageView);
or
vBox.getChildern().add(scrollPane);
vBox.getChildern.add(canvasRef);
- Fourth step is creating scene for apply show method on to it.
Syntax:
Scene screen = new Scene(vBox, length, width);
- Adding Scene reference screen to the Stage object reference is fifth step. Adding output screen to Stage. We will get this stage object reference from start predefined JavaFX method.
Syntax:
stage.setScene(screen);
- Sixth step is showing output to the end user by applying show () method on the scene object.
Syntax:
stage.show();
Examples of JavaFX Game
Given below are the examples:
Example #1
Canvas Demo with an Image.
Code:
package com.game;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
public class CanvasDemo extends Application {
public void start(Stage stageOutput) {
// setting the title to the application
stageOutput.setTitle("Canvas Demo");
// creating group object
Group groupRef = new Group();
// creating scene object and add the group
Scene sceneRef = new Scene(groupRef);
stageOutput.setScene(sceneRef);
// Creating canvas object for add an image
Canvas canvasRef = new Canvas(600, 500);
groupRef.getChildren().add(canvasRef);
// adding 2d graphics to the canvas object
GraphicsContextgraphicCOntext = canvasRef.getGraphicsContext2D();
// adding color to the graphic
graphicCOntext.setFill(Color.BLUE);
// adding stroke color to graphic
graphicCOntext.setStroke(Color.BROWN);
// adding line width
graphicCOntext.setLineWidth(3);
// setting font
Font theFont = Font.font("Times New Roman", FontWeight.BOLD, 48);
graphicCOntext.setFont(theFont);
// adding text to the application
graphicCOntext.fillText("Hi, I am Canvas Demo", 61, 52);
graphicCOntext.strokeText("Hi, I am Canvas Demo", 61, 52);
// creating an image object
Image earth = new Image("s2.jpg");
// draw the image on the application
graphicCOntext.drawImage(earth, 182, 102);
// dsiplay the output
stageOutput.show();
}
public static void main(String args[])
// JVM calls start method automatically
launch(args);
}
}
Output:
Example #2
Timer with moving moon around sun.
Code:
package com.game;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import javafx.stage.Stage;
public class TimerDemo extends Application {
public void start(Stage outStageObject)
{
//setting the title to the application
outStageObject.setTitle( "Timer Demo" );
Group groupObject = new Group();
Scene scenRef = new Scene( groupObject );
outStageObject.setScene( scenRef );
//creating canvas object
Canvas canvasRef = new Canvas( 600, 512 );
groupObject.getChildren().add( canvasRef );
// adding 2d graphics to the canvas object
GraphicsContextgraphicsContext= canvasRef.getGraphicsContext2D();
//creating image for draw them on the out screen
Image moonImage = new Image( "m1.jpg" );
Image sunImAGE = new Image( "s2.jpg" );
//getting nano time for time interval operation within the AnimationTimer() constructor
final long tempNanoTIme = System.nanoTime();
//this function makes the moon to revolving around the sun with some time interval
new AnimationTimer()
{
//handler method for timer
public void handle(long presentNanoTime)
{
double time = (presentNanoTime - tempNanoTIme) / 1000000000;
double xAxis = 231 + 127 * Math.cos(time);
double yAxis = 231 + 127 * Math.sin(time);
// background images for timer functionality illustration
graphicsContext.drawImage( moonImage, xAxis, yAxis );
graphicsContext.drawImage( sunImAGE, 196, 196 );
}
}.start();
outStageObject.show();
}
public static void main(String args[]) {
// JVM calls start method automatically
launch(args);
}
}
Output:
Example #3
Keyboard Action left and right button with Images.
Code:
package com.game;
import java.util.ArrayList;
import java.util.List;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;
public class MouseEvent extends Application {
public void start(Stage outputStageObject) {
// setting title to the application
outputStageObject.setTitle("Keyboard Events Demo");
// creating the group object
Group groupRef = new Group();
// creating the scene object
Scene sceneObject = new Scene(groupRef);
outputStageObject.setScene(sceneObject);
// creating canvas object
Canvas canvasObject = new Canvas(500, 400);
groupRef.getChildren().add(canvasObject);
// Creating array list object
List<String>arrayListObjectString = new ArrayList<String>();
// setting keyword pressing event by setOnKeyPressed method
sceneObject.setOnKeyPressed(new EventHandler<KeyEvent>() {
public void handle(KeyEventkeyEvent) {
String contnet = keyEvent.getCode().toString();
// overcomes duplicate data
if (!arrayListObjectString.contains(contnet))
arrayListObjectString.add(contnet);
}
});
// setting keyword pressing event by setOnKeyReleased method
sceneObject.setOnKeyReleased(new EventHandler<KeyEvent>() {
public void handle(KeyEventkeyEvet) {
String content = keyEvet.getCode().toString();
arrayListObjectString.remove(content);
}
});
// adding 2d graphics to the canvas object
GraphicsContextgraphicContext = canvasObject.getGraphicsContext2D();
// Creating left and right images
Image leftImage1 = new Image("L1.jpg");
Image leftImage2 = new Image("L2.jpg");
Image rightImage1 = new Image("R1.jpg");
Image rightImage2 = new Image("R2.jpg");
// this function makes the moon to revolving around the sun with some
// time interval
new AnimationTimer() {
// handler method for timer
public void handle(long currentNanoTime) {
// clearing the canvas
graphicContext.clearRect(0, 0, 520, 520);
// checking whether left key is pressed
if (arrayListObjectString.contains("LEFT"))
graphicContext.drawImage(leftImage2, 65, 65);
else
graphicContext.drawImage(leftImage1, 65, 65);
// checking whether right key is pressed
if (arrayListObjectString.contains("RIGHT"))
graphicContext.drawImage(rightImage2, 260, 65);
else
graphicContext.drawImage(rightImage1, 260, 65);
}
}.start();
// displaying output
outputStageObject.show();
}
public static void main(String args[]) {
// JVM calls start method automatically
launch(args);
}
}
Output:
Conclusion
JavaFX game can be done by using canvas, keyboard actions, and mouse event actions etc classes. This application are more easy to develop and easy to use. We can add animations for better visibility of the JavaFX games.
Recommended Articles
This is a guide to JavaFX Game. Here we discuss the introduction, frequently used constructors, methods and how does game work in JavaFX along with respective examples. You may also have a look at the following articles to learn more –