JAVA — CHAPTER 17

JavaFX Graphics and Multimedia · Cheat Sheet
CSS Styling 2D Shapes Transforms Media/Video Animations Canvas
1 STYLING WITH CSS
/* style.css */ .label-title { -fx-font-size: 20px; -fx-font-weight: bold; -fx-text-fill: #333; } // applying it in Java: scene.getStylesheets().add("style.css"); label.getStyleClass().add("label-title");

Why CSS in JavaFX

JavaFX supports CSS-like stylesheets (properties prefixed -fx-) so visual styling stays separate from layout/application logic — same idea as web CSS.

2 2D SHAPES, POLYLINES, POLYGONS & PATHS

Basic shapes

  • Circle, Rectangle, Ellipse, Line
  • Set fill/stroke colors, position, size

Polyline / Polygon

Defined by a list of x,y coordinate pairs — Polyline is open, Polygon auto-closes back to the start.

Path

Built from path elements (MoveTo, LineTo, ArcTo) for complex/curved outlines.

3 TRANSFORMS
Rectangle r = new Rectangle(50, 50, 100, 60); r.setRotate(45); r.getTransforms().add(new Scale(1.5, 1.5)); r.getTransforms().add(new Translate(20, 0));

Transform types

  • Rotate — spins a node around a point
  • Scale — resizes a node
  • Translate — moves a node by an offset
4 PLAYING VIDEO: Media, MediaPlayer & MediaView
Media media = new Media(new File("clip.mp4").toURI().toString()); MediaPlayer player = new MediaPlayer(media); MediaView view = new MediaView(player); player.play();

Three collaborating classes

  • Media — the media file/source
  • MediaPlayer — controls playback (play, pause, volume)
  • MediaView — the visual Node that displays it
5 ANIMATIONS: TRANSITIONS, TIMELINE & AnimationTimer

Transition classes

FadeTransition ft = new FadeTransition( Duration.seconds(2), node); ft.setFromValue(1); ft.setToValue(0); ft.play();

Timeline

Defines KeyFrames at specific times, animating any property value in between — flexible, multi-step animation.

AnimationTimer

Calls its handle(now) method every frame (~60 fps) — used for game loops needing per-frame control.

6 DRAWING ON A Canvas & 3D SHAPES
Canvas canvas = new Canvas(300, 200); GraphicsContext gc = canvas.getGraphicsContext2D(); gc.setFill(Color.BLUE); gc.fillRect(10, 10, 100, 50);

Canvas vs. Shape nodes

A Canvas is an immediate-mode drawing surface (like painting pixels) — great for custom graphics, charts, or games — versus individual Shape nodes which remain live objects in the scene graph.

3D shapes (Box, Sphere, Cylinder) plus a PerspectiveCamera enable simple 3D scenes.