Welcome guys. Learn the JavaFX UI widgets using these code snippets.
Example 1: Gfx2d
Let us look at the code
Step 1: Create Project
- Open your favorite Java IDE.
- In the menu go to
File --> Create New Project
.
Step 2: Dependencies
No dependencies are needed for this project.
Step 3: Write Code
Our code will comprise the following java files:
Gfx2DExample.java
- In your editor or IDE, create a file known as
Gfx2DExample.java
. - Then add the following code:
(a). Gfx2DExample.java
We will need functionalities injected into this class via ready made classes. But first we have to import them. Let’s go ahead and do just that:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
Extend the class
as shown below:
public class Gfx2DExample extends Application {
Our class
will have the following methods:
void main(String[] args)
void start(Stage primaryStage)
We will add a main method to our Java class as shown below:
public static void main(String[] args) {
Here is the full code:
package com.jenkov.javafx.gfx2d;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class Gfx2DExample extends Application {
public static void main(String[] args) {
launch(args);
}
public void start(Stage primaryStage) {
Circle circle = new Circle();
circle.setCenterX(100);
circle.setCenterY(100);
circle.setRadius(125);
circle.setStroke(Color.valueOf("#ff00ff"));
circle.setStrokeWidth(5);
circle.setFill(Color.TRANSPARENT);
Rectangle rectangle = new Rectangle();
rectangle.setX(200);
rectangle.setY(200);
rectangle.setWidth(300);
rectangle.setHeight(400);
rectangle.setStroke(Color.TRANSPARENT);
rectangle.setFill(Color.valueOf("#00ffff"));
Pane pane = new Pane();
pane.getChildren().add(circle);
pane.getChildren().add(rectangle);
Scene scene = new Scene(pane, 1024, 800, true);
primaryStage.setScene(scene);
primaryStage.setTitle("2D Example");
primaryStage.show();
}
}
Download
Download the code using the below links:
Number | Link |
---|---|
1. | Download Example |
2. | Follow code author |
3. | Code: Apache 2.0 License |