JavaFX Graphics

Creating visual elements and custom graphics

🎨 What are JavaFX Graphics?

JavaFX Graphics provide powerful tools for creating shapes, drawings, animations, and visual effects. You can draw custom graphics, manipulate images, and create rich visual experiences in your applications.


// Simple Graphics Example
Circle circle = new Circle(50, Color.BLUE);
Rectangle rectangle = new Rectangle(100, 60, Color.RED);
Line line = new Line(0, 0, 100, 100);

Pane canvas = new Pane();
canvas.getChildren().addAll(circle, rectangle, line);
                                    

Output:

Graphics Elements

🔴

Basic Shapes

Circles, rectangles, polygons, and lines

Circle circle = new Circle(30, Color.RED);
Rectangle rect = new Rectangle(60, 40);
🖼️

Images

Loading and displaying images

Image img = new Image("file:image.png");
ImageView imageView = new ImageView(img);
🎨

Canvas

Custom drawing with GraphicsContext

Canvas canvas = new Canvas(300, 200);
GraphicsContext gc = canvas.getGraphicsContext2D();

Effects

Shadows, blurs, and transformations

DropShadow shadow = new DropShadow();
shape.setEffect(shadow);

🔹 Basic Shapes

Creating and customizing basic geometric shapes:

// Circle
Circle circle = new Circle();
circle.setCenterX(100);
circle.setCenterY(100);
circle.setRadius(50);
circle.setFill(Color.LIGHTBLUE);
circle.setStroke(Color.DARKBLUE);
circle.setStrokeWidth(3);

// Rectangle
Rectangle rectangle = new Rectangle();
rectangle.setX(200);
rectangle.setY(50);
rectangle.setWidth(120);
rectangle.setHeight(80);
rectangle.setFill(Color.LIGHTGREEN);
rectangle.setArcWidth(10);  // Rounded corners
rectangle.setArcHeight(10);

// Polygon (Triangle)
Polygon triangle = new Polygon();
triangle.getPoints().addAll(new Double[]{
    50.0, 200.0,   // Point 1
    100.0, 150.0,  // Point 2
    150.0, 200.0   // Point 3
});
triangle.setFill(Color.ORANGE);

// Line
Line line = new Line();
line.setStartX(0);
line.setStartY(250);
line.setEndX(300);
line.setEndY(250);
line.setStroke(Color.BLACK);
line.setStrokeWidth(2);

Output:

🔹 Canvas Drawing

Using Canvas for custom graphics and drawing operations:

Canvas canvas = new Canvas(400, 300);
GraphicsContext gc = canvas.getGraphicsContext2D();

// Set drawing properties
gc.setFill(Color.BLUE);
gc.setStroke(Color.RED);
gc.setLineWidth(3);

// Draw shapes
gc.fillOval(50, 50, 100, 80);        // Filled oval
gc.strokeRect(200, 50, 120, 80);     // Rectangle outline
gc.fillPolygon(new double[]{50, 100, 150}, 
               new double[]{200, 150, 200}, 3); // Triangle

// Draw text
gc.setFill(Color.BLACK);
gc.setFont(Font.font("Arial", FontWeight.BOLD, 16));
gc.fillText("Canvas Graphics", 150, 250);

// Draw lines and curves
gc.setStroke(Color.GREEN);
gc.strokeLine(0, 280, 400, 280);     // Straight line

// Bezier curve
gc.beginPath();
gc.moveTo(50, 280);
gc.bezierCurveTo(100, 240, 200, 320, 250, 280);
gc.stroke();

Output:

Canvas Graphics

🔹 Working with Images

Loading, displaying, and manipulating images:

// Load image from file
Image image = new Image("file:resources/photo.jpg");

// Create ImageView
ImageView imageView = new ImageView(image);
imageView.setFitWidth(200);
imageView.setFitHeight(150);
imageView.setPreserveRatio(true);

// Image effects
ColorAdjust colorAdjust = new ColorAdjust();
colorAdjust.setBrightness(0.2);
colorAdjust.setContrast(0.1);
imageView.setEffect(colorAdjust);

// Image with Canvas
Canvas imageCanvas = new Canvas(300, 200);
GraphicsContext gc = imageCanvas.getGraphicsContext2D();

// Draw image on canvas
gc.drawImage(image, 0, 0, 150, 100);

// Draw over the image
gc.setFill(Color.WHITE);
gc.setFont(Font.font("Arial", FontWeight.BOLD, 20));
gc.fillText("Overlay Text", 10, 90);

// Create image from canvas
WritableImage snapshot = imageCanvas.snapshot(null, null);
ImageView snapshotView = new ImageView(snapshot);

Output:

Original
Overlay Text

🔹 Visual Effects

Adding shadows, blurs, and other visual effects:

// Drop Shadow Effect
DropShadow dropShadow = new DropShadow();
dropShadow.setColor(Color.GRAY);
dropShadow.setOffsetX(5);
dropShadow.setOffsetY(5);
dropShadow.setRadius(10);

Button shadowButton = new Button("Drop Shadow");
shadowButton.setEffect(dropShadow);

// Glow Effect
Glow glow = new Glow();
glow.setLevel(0.7);

Button glowButton = new Button("Glow Effect");
glowButton.setEffect(glow);

// Blur Effect
GaussianBlur blur = new GaussianBlur();
blur.setRadius(5);

Label blurLabel = new Label("Blurred Text");
blurLabel.setEffect(blur);

// Reflection Effect
Reflection reflection = new Reflection();
reflection.setFraction(0.5);
reflection.setTopOffset(2);

Text reflectionText = new Text("Reflection");
reflectionText.setFont(Font.font("Arial", FontWeight.BOLD, 24));
reflectionText.setFill(Color.DARKBLUE);
reflectionText.setEffect(reflection);

// Combining Effects
DropShadow combinedShadow = new DropShadow();
combinedShadow.setColor(Color.BLACK);
combinedShadow.setOffsetX(3);
combinedShadow.setOffsetY(3);

Glow combinedGlow = new Glow();
combinedGlow.setLevel(0.5);
combinedGlow.setInput(combinedShadow);

Button combinedButton = new Button("Combined Effects");
combinedButton.setEffect(combinedGlow);

Output:

Blurred Text
Reflection Reflection

🔹 Transformations

Rotating, scaling, and translating graphics elements:

// Create shapes for transformation
Rectangle originalRect = new Rectangle(50, 30, Color.BLUE);
Rectangle rotatedRect = new Rectangle(50, 30, Color.RED);
Rectangle scaledRect = new Rectangle(50, 30, Color.GREEN);

// Rotation Transform
Rotate rotation = new Rotate();
rotation.setAngle(45);
rotation.setPivotX(25);  // Center of rectangle
rotation.setPivotY(15);
rotatedRect.getTransforms().add(rotation);

// Scale Transform
Scale scale = new Scale();
scale.setX(1.5);  // 150% width
scale.setY(0.8);  // 80% height
scaledRect.getTransforms().add(scale);

// Translation (moving)
Translate translate = new Translate();
translate.setX(100);
translate.setY(50);
scaledRect.getTransforms().add(translate);

// Animation with Timeline
Timeline timeline = new Timeline();
KeyFrame keyFrame = new KeyFrame(Duration.seconds(2),
    new KeyValue(rotation.angleProperty(), 360));
timeline.getKeyFrames().add(keyFrame);
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.play();

// Group transformations
Group transformGroup = new Group();
transformGroup.getChildren().addAll(originalRect, rotatedRect, scaledRect);

// Apply group transformation
transformGroup.setRotate(15);
transformGroup.setScaleX(1.2);
transformGroup.setScaleY(1.2);

Output:

🔹 Complete Graphics Example

A comprehensive example combining multiple graphics features:

public class GraphicsDemo extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        Pane root = new Pane();
        root.setPrefSize(500, 400);
        
        // Background gradient
        Rectangle background = new Rectangle(500, 400);
        LinearGradient gradient = new LinearGradient(0, 0, 0, 1, true, 
            CycleMethod.NO_CYCLE,
            new Stop(0, Color.LIGHTBLUE),
            new Stop(1, Color.LIGHTGREEN));
        background.setFill(gradient);
        
        // Sun (circle with glow)
        Circle sun = new Circle(100, 80, 40, Color.YELLOW);
        Glow sunGlow = new Glow(0.8);
        sun.setEffect(sunGlow);
        
        // Mountains (polygons)
        Polygon mountain1 = new Polygon();
        mountain1.getPoints().addAll(new Double[]{
            0.0, 300.0, 150.0, 150.0, 300.0, 300.0
        });
        mountain1.setFill(Color.DARKGREEN);
        
        Polygon mountain2 = new Polygon();
        mountain2.getPoints().addAll(new Double[]{
            200.0, 300.0, 350.0, 100.0, 500.0, 300.0
        });
        mountain2.setFill(Color.GREEN);
        
        // House (rectangle + triangle roof)
        Rectangle house = new Rectangle(350, 250, 80, 60);
        house.setFill(Color.BROWN);
        
        Polygon roof = new Polygon();
        roof.getPoints().addAll(new Double[]{
            340.0, 250.0, 390.0, 200.0, 440.0, 250.0
        });
        roof.setFill(Color.DARKRED);
        
        // Door and window
        Rectangle door = new Rectangle(370, 280, 15, 30);
        door.setFill(Color.DARKBROWN);
        
        Rectangle window = new Rectangle(395, 265, 20, 15);
        window.setFill(Color.LIGHTBLUE);
        window.setStroke(Color.BLACK);
        
        // Add all elements
        root.getChildren().addAll(background, mountain1, mountain2, 
                                 sun, house, roof, door, window);
        
        Scene scene = new Scene(root);
        primaryStage.setTitle("JavaFX Graphics Demo");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

🧠 Test Your Knowledge

Which class is used for custom drawing operations in JavaFX?