Home
13GUI, Graphics, Databases & Spring
13

Topic 13 of 13 · Lecture 24

GUI, Graphics, Databases & Spring

Building desktop interfaces with JavaFX components and layouts, handling events, drawing and animating graphics, connecting to a database with JDBC, and a first look at the Spring framework.

← → move between slides · F full screen · M slide list

Before we start

Why this matters

Every app you use has buttons, text boxes and pictures, and saves your data somewhere. How much of that can you already build with the OOP you know?

All of it. A JavaFX window is a tree of objects; a button click is an event object delivered to a method; a database row becomes a Java object. Classes, inheritance, interfaces and lambdas are everywhere.

This last topic tours the libraries you will use for real projects: JavaFX for interfaces and graphics, JDBC for databases and Spring for back-end services.

Concept 1 of 5

A JavaFX application

Stage (window) → Scene → scene graph of nodes: layout panes containing controls.

A JavaFX application

public class HelloFX extends Application {
    @Override
    public void start(Stage stage) {
        Label msg = new Label("Hello, JavaFX");
        Button btn = new Button("Click me");
        btn.setOnAction(e -> msg.setText("Clicked!"));

        VBox root = new VBox(10, msg, btn);    // layout pane
        stage.setScene(new Scene(root, 300, 150));
        stage.setTitle("First FX app");
        stage.show();
    }
    public static void main(String[] args) { launch(args); }
}
  • Extend Application and override start(Stage); launch() calls it for you.
  • Everything you see is a Node object in a tree.

Concept 2 of 5

Components (controls)

ControlUseUseful methods
LabelShow textsetText, setFont
ButtonTrigger an actionsetOnAction
TextField / PasswordFieldType one linegetText, setPromptText
TextAreaSeveral linesgetText, appendText
CheckBoxYes/no optionisSelected
RadioButton + ToggleGroupOne choice of manygetSelectedToggle
ComboBox / ChoiceBoxDrop-down listgetItems().addAll, getValue
ListView / TableViewLists and tables of objectsgetItems, getSelectionModel
ImageViewShow a picturenew ImageView(new Image(url))

Interactive

JavaFX layout playground

Concept 3 of 5

Event handling

The user acts; the control creates an event object and calls every registered handler.
// 1. lambda (most common)
btn.setOnAction(e -> System.out.println("clicked"));

Concept 3 of 5

Event handling (cont.)

// 2. anonymous class implementing EventHandler<ActionEvent>
btn.setOnAction(new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent e) { System.out.println("clicked"); }
});

// other events
field.setOnKeyPressed(e -> System.out.println(e.getCode()));
canvas.setOnMouseClicked(e -> System.out.println(e.getX() + "," + e.getY()));

Code example

Designing a simple interface

GridPane g = new GridPane(); g.setHgap(10); g.setVgap(8); g.setPadding(new Insets(16)); TextField marks = new TextField(); marks.setPromptText("0 - 100"); Button calc = new Button("Get grade"); Label result = new Label(); g.add(new Label("Marks:"), 0, 0); g.add(marks, 1, 0); g.add(calc, 1, 1); g.add(result, 1, 2); calc.setOnAction(e -> { try { int m = Integer.parseInt(marks.getText().trim()); result.setText(m >= 80 ? "A+" : m >= 70 ? "A" : m >= 60 ? "A-" : "Below A-"); } catch (NumberFormatException ex) { result.setText("Please enter a whole number"); } }); stage.setScene(new Scene(g));
The window after typing 76 and clicking
┌ Grade calculator ─────────────┐
│ Marks:  [ 76            ]     │
│         [ Get grade ]         │
│         A                     │
└───────────────────────────────┘

Layout pane + controls + one event handler with exception handling: every OOP idea in one small form.

Step through the code

Trace: an event handler runs later

Registering a handler runs nothing. Choose what the user types, then watch the click call the lambda.

Step through the code

Trace: an event handler runs later (cont.)

Interactive · code example

Drawing graphics on a Canvas

Canvas canvas = new Canvas(400, 250);
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFill(Color.LIGHTBLUE);   gc.fillRect(0, 0, 400, 250);
gc.setFill(Color.GOLD);        gc.fillOval(300, 30, 60, 60);
gc.setFill(Color.FORESTGREEN); gc.fillRect(0, 190, 400, 60);
gc.setFill(Color.SIENNA);      gc.fillRect(80, 120, 120, 70);
gc.setFill(Color.DARKRED);
gc.fillPolygon(new double[]{70, 140, 210}, new double[]{120, 70, 120}, 3);
gc.setFill(Color.KHAKI);       gc.fillRect(125, 150, 30, 40);
gc.setStroke(Color.BLACK);     gc.setLineWidth(2);
gc.strokeLine(0, 190, 400, 190);
gc.setFill(Color.BLACK);       gc.fillText("My house", 110, 215);

Interactive

Animation with AnimationTimer

Concept 4 of 5

Connecting to a database with JDBC

The standard JDBC steps.

Concept 4 of 5

Connecting to a database with JDBC (cont.)

  1. Add the driver (e.g. MySQL Connector/J) to the project.
  2. DriverManager.getConnection(url, user, password) opens a Connection.
  3. Create a PreparedStatement with ? placeholders and fill them with setString, setInt, …
  4. executeQuery() returns a ResultSet (SELECT); executeUpdate() returns a row count (INSERT/UPDATE/DELETE).
  5. Close everything — try-with-resources does it for you.

Step through the code

Trace: a ResultSet cursor, row by row

Follow the objects JDBC creates and the cursor moving through the result, then everything closing in reverse order.

Step through the code

Trace: a ResultSet cursor, row by row (cont.)

Interactive

JDBC query walk-through

Code example

Inserting rows safely

String url = "jdbc:mysql://localhost:3306/gub";
String sql = "INSERT INTO students(name, dept, cgpa) VALUES (?, ?, ?)";
try (Connection con = DriverManager.getConnection(url, "root", "secret");
     PreparedStatement ps = con.prepareStatement(sql)) {
    ps.setString(1, "Farhan");
    ps.setString(2, "CSE");
    ps.setDouble(3, 3.80);
    int rows = ps.executeUpdate();
    System.out.println(rows + " row inserted");
} catch (SQLException e) {
    System.out.println("DB error: " + e.getMessage());
}
Output
1 row inserted

Code example

Inserting rows safely (cont.)

Security: Never build SQL by joining user input: "… WHERE name = '" + input + "'" lets a user type ' OR '1'='1 and read every row (SQL injection). PreparedStatement parameters are always treated as data.

Concept 5 of 5

Introduction to Spring

@SpringBootApplication
public class GradeApp {
    public static void main(String[] args) {
        SpringApplication.run(GradeApp.class, args);
    }
}

@Service
class GradeService {
    String letter(int m) { return m >= 80 ? "A+" : m >= 70 ? "A" : "below A"; }
}

@RestController
class GradeController {
    private final GradeService service;
    GradeController(GradeService service) {   // injected by Spring
        this.service = service;

Concept 5 of 5

Introduction to Spring (cont.)

    }
    @GetMapping("/grade/{marks}")
    String grade(@PathVariable int marks) { return service.letter(marks); }
}
Browser
GET http://localhost:8080/grade/85   →   A+
  • Spring is the most widely used Java framework for back-end and web applications.
  • Inversion of Control / Dependency Injection: you declare what an object needs (a constructor parameter); Spring creates the objects and wires them together.
  • Spring Boot adds sensible defaults and an embedded web server, so a REST API is a few annotated classes.
  • Spring Data JPA maps classes to database tables, replacing most hand-written JDBC.

Worked example 1 of 3

Worked example 1

Which layout pane would you use for a login form with labels in one column and fields in the next?
Show the solution
GridPane — it places nodes in rows and columns: g.add(new Label("User"), 0, 0); g.add(userField, 1, 0);.

Worked example 2 of 3

Worked example 2

Write a handler that shows the length of the text typed in TextField tf in Label lb whenever the user presses Enter.
Show the solution
tf.setOnAction(e -> lb.setText("Length: " + tf.getText().length()));
For a TextField, setOnAction fires when Enter is pressed.

Worked example 3 of 3

Worked example 3

Loop through a ResultSet and build a list of Student objects.
Show the solution
List<Student> list = new ArrayList<>();
try (ResultSet rs = ps.executeQuery()) {
    while (rs.next())
        list.add(new Student(rs.getString("name"), rs.getDouble("cgpa")));
}
Each row becomes one object — the bridge between tables and OOP.

Practice

Practice (1 of 2)

Try each one on paper first, then check your answer.

1. What are Stage, Scene and Node in JavaFX?
Show the answer
Stage is the window; Scene is the content shown in it; Nodes are the objects (panes, controls, shapes) in the scene graph tree.
2. Write code that draws a red circle of radius 40 centred at (100, 100) on a GraphicsContext gc.
Show the answer
gc.setFill(Color.RED);
gc.fillOval(60, 60, 80, 80);   // top-left corner, width, height
3. Why must slow work (like a database query) not run inside an event handler on the JavaFX Application Thread?
Show the answer
The UI thread would be blocked, so the window freezes. Run the work in a background thread (e.g. a Task) and update the UI with Platform.runLater.

Practice

Practice (2 of 2)

Try each one on paper first, then check your answer.

4. What is the difference between executeQuery and executeUpdate?
Show the answer
executeQuery runs a SELECT and returns a ResultSet; executeUpdate runs INSERT/UPDATE/DELETE and returns the number of affected rows.
5. Explain dependency injection in one sentence.
Show the answer
Instead of an object creating the objects it needs, they are passed to it (usually through the constructor) by a container such as Spring.
6. How does an AnimationTimer create smooth motion?
Show the answer
Its handle(now) method is called about 60 times per second; each call updates positions slightly and redraws the frame.

Check yourself

Quiz

Summary

Summary

  • A JavaFX app is a Stage showing a Scene whose root is a tree of nodes: layout panes and controls.
  • Layouts (HBox, VBox, GridPane, BorderPane, FlowPane, StackPane) position controls; events call handlers, usually lambdas.
  • Canvas + GraphicsContext draw shapes and text; AnimationTimer redraws ~60 times a second for animation.
  • JDBC: Connection → PreparedStatement → ResultSet, closed with try-with-resources.
  • Spring Boot builds back-end services from annotated classes wired together by dependency injection.