Example app
Keyboard movement
Arrow keys move a circle and keep it inside the canvas.
Run this example
Stop the app and save your current Main and helpers outside src/. Copy the files shown below into the listed destinations in your standalone starter, creating resource folders when needed. Replace Main and the listed helpers. Keep the zero/ framework folder and build files. If an older downloaded kit does not have these examples, use the source shown here.
- examples/keyboard/Main.java →
src/main/java/Main.java - examples/keyboard/Mover.java →
src/main/java/Mover.java
Run App to rebuild. Click the canvas before testing input. These examples run in VS Code, in a separate JavaFX window.
Open related lessonRead the source
keyboard/Main.java
import javafx.scene.input.KeyCode;
import javafx.scene.paint.Color;
import zero.SketchApp;
/** Arrow keys move an ordinary object. Main decides when to update it. */
public class Main extends SketchApp {
private Mover mover;
@Override
public void settings() {
size(640, 400);
title("Arrow-key movement");
}
@Override
public void setup() {
mover = new Mover(width() / 2, height() / 2);
}
@Override
public void update(double seconds) {
int horizontal = 0;
int vertical = 0;
if (keyDown(KeyCode.LEFT)) horizontal--;
if (keyDown(KeyCode.RIGHT)) horizontal++;
if (keyDown(KeyCode.UP)) vertical--;
if (keyDown(KeyCode.DOWN)) vertical++;
mover.update(horizontal, vertical, seconds, width(), height());
}
@Override
public void draw() {
background(Color.ALICEBLUE);
fill(Color.DARKSLATEGRAY);
textSize(20);
text("Hold the arrow keys to move.", 20, 30);
mover.draw(this);
}
public static void main(String[] args) {
launch(args);
}
}
keyboard/Mover.java
import javafx.scene.paint.Color;
import zero.SketchApp;
/** This is a Java object, not a framework-managed game entity. */
public class Mover {
private double x;
private double y;
private final double radius = 18;
private final double speed = 180; // Pixels per second on each axis.
public Mover(double x, double y) {
this.x = x;
this.y = y;
}
public void update(int horizontal, int vertical, double seconds,
double width, double height) {
x += horizontal * speed * seconds;
y += vertical * speed * seconds;
// Keep the whole circle inside the canvas.
x = Math.max(radius, Math.min(width - radius, x));
y = Math.max(radius, Math.min(height - radius, y));
}
public void draw(SketchApp app) {
app.fill(Color.CORNFLOWERBLUE);
app.circle(x, y, radius * 2);
}
}