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.
Outline · Lecture 24
Topics in this chapter
Select a topic to jump to the slide that explains it.
Concept 1 of 5
A JavaFX application
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
Applicationand overridestart(Stage);launch()calls it for you. - Everything you see is a Node object in a tree.
Concept 2 of 5
Components (controls)
| Control | Use | Useful methods |
|---|---|---|
| Label | Show text | setText, setFont |
| Button | Trigger an action | setOnAction |
| TextField / PasswordField | Type one line | getText, setPromptText |
| TextArea | Several lines | getText, appendText |
| CheckBox | Yes/no option | isSelected |
| RadioButton + ToggleGroup | One choice of many | getSelectedToggle |
| ComboBox / ChoiceBox | Drop-down list | getItems().addAll, getValue |
| ListView / TableView | Lists and tables of objects | getItems, getSelectionModel |
| ImageView | Show a picture | new ImageView(new Image(url)) |
Interactive
JavaFX layout playground
Concept 3 of 5
Event handling
// 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));┌ 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
Concept 4 of 5
Connecting to a database with JDBC (cont.)
- Add the driver (e.g. MySQL Connector/J) to the project.
DriverManager.getConnection(url, user, password)opens aConnection.- Create a
PreparedStatementwith?placeholders and fill them withsetString,setInt, … executeQuery()returns aResultSet(SELECT);executeUpdate()returns a row count (INSERT/UPDATE/DELETE).- 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());
}1 row inserted
Code example
Inserting rows safely (cont.)
"… 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); }
}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
Show the solution
g.add(new Label("User"), 0, 0); g.add(userField, 1, 0);.Worked example 2 of 3
Worked example 2
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
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.
Show the answer
Show the answer
gc.setFill(Color.RED); gc.fillOval(60, 60, 80, 80); // top-left corner, width, height
Show the answer
Practice
Practice (2 of 2)
Try each one on paper first, then check your answer.
Show the answer
Show the answer
Show the answer
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.