How to summarize the logic I used to draw lines as key is pressed?

I am solving this problem:

Draw lines using the arrow keys. Write a program that draws line segments using the arrow keys. The line starts from the center of the pane and draws towards east, north, west, or south when the right-arrow key, up-arrow key, left-arrow key, or down-arrow key is pressed.

Here’s my code:

package com.example.demo;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Line;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class DisplayMousePosition extends Application {
    Pane pane = new Pane();
    Line line = new Line(300, 100, 200, 100);
    double x1, y1, x2, y2;
    double delta = 50;

    @Override
    public void start(Stage primaryStage) {
        //Line(double startX, double startY, double endX, double endY)
        //Creates a new instance of Line.
        x1 = 200;
        y1 = 100;
        x2 = 300;
        y2 = 100;
        pane.getChildren().add(line);
        pane.setOnKeyPressed(e -> {
            switch (e.getCode()) {
                case DOWN:
                    x1 = x2;
                    y1 = y2;
                    y2 = y1 + delta;
                    pane.getChildren().add(new Line(x1, y1, x2, y2));
                    break;
                case UP:
                    x1 = x2;
                    y1 = y2;
                    y2 = y2 - delta;
                    pane.getChildren().add(new Line(x1, y1, x2, y2));
                    break;
                case LEFT:
                    x1 = x2;
                    y1 = y2;
                    y2 = y1;
                    x2 = x1 - delta;
                    pane.getChildren().add(new Line(x1, y1, x2, y2));
                    break;
                case RIGHT:
                    x1 = x2;
                    y1 = y2;
                    x2 = x1 + delta;
                    y2 = y1;
                    pane.getChildren().add(new Line(x1, y1, x2, y2));
                    break;
            }
        });

        Scene scene = new Scene(pane, 500, 500);
        primaryStage.setScene(scene);
        primaryStage.show();
        line.requestFocus();// for line to receive and accept keyboard input
    }
}

I wrote this on my own without using chatgpt or deepseek etc. I know better way of coding this does exist.

However, I want to formally summarize my logic.

This was how I came to this logic. But I don’t find a simple way to summarize it. Maybe because my logic looks too complicated.

I didn’t look at your logic in great detail, but the main thing to remember is that a handful of points in each direction won’t change. For example, when you are moving the arrow up/down, the X positions will stay the same. The flipside is true when you are moving the arrow left/right where the Y positions will stay the same.

As long as you have that, you are good!

1 Like