JavaFX z Arią - powrót do strony głównej

FXML tutorial (22) – element JavaFX Canvas w FXML

Listing22_Controller.java
package codes;

import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;

import java.net.URL;
import java.util.ResourceBundle;

public class Listing22_Controller implements Initializable {

    @FXML
    private Canvas cv ;
    private GraphicsContext gc ;
    @FXML
    private void drawChessboard(double x, double y, double size) {
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                if ((i + j) % 2 != 0) {
                    gc.fillRect(x, y, size / 8.0, size / 8.0);
                }
                gc.translate(size / 8.0, 0);
            }
            gc.translate(-size, size / 8.0);
        }
        gc.strokeRect(x, y - size, size, size);
    }
   @Override
    public void initialize(URL location, ResourceBundle resources) {
       gc = cv.getGraphicsContext2D();
       gc.setFill(Color.BLACK);
       gc.setStroke(Color.BLACK);
       gc.setFill(Color.BLACK);
       gc.setStroke(Color.BLACK);
       drawChessboard(50, 50, 300);
    }


}
listing22_canvas.fxml
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.canvas.Canvas?>
<?import javafx.scene.Group?>
<Group xmlns="http://javafx.com/javafx/19" xmlns:fx="http://javafx.com/fxml/1" fx:controller="codes.Listing22_Controller">
     <Canvas fx:id="cv" height="400" width="400" />
</Group>
Listing22_xanvas.java

Klasa uruchamiająca.

package codes;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.net.URL;

public class Listing22_canvas extends Application {
    public static void main(String[] args) {
        Application.launch(args);
    }

    @Override
    public void start(Stage stage) {
        try {
            URL fxmlUrl = this.getClass().getClassLoader()
                    .getResource("resources/listing22_canvas.fxml");
            Group root = fxmlUrl != null ? FXMLLoader.load(fxmlUrl) : new Group();
            Scene scene = new Scene(root, 400, 400);
            stage.setScene(scene);
            stage.setTitle("Szachownica");
            stage.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Po uruchomieniu zobaczymy:

Szachownica