public void setCanvas(Canvas canvas) {
this.canvas = canvas;
}
public void drawLine(GraphicsContext graphicsContext, Point point1, Point point2, int operation) {
if (operation >= 1) {
drawWuLine(graphicsContext, point1, point2);
} else if (operation == 0) {
drawBresenhamLine(graphicsContext, point1, point2);
} else {
drawDDALine(graphicsContext, point1, point2);
}
}
private void drawWuLine(GraphicsContext graphicsContext, Point point1, Point point2) {
int x0 = point1.getX();
int y0 = point1.getY();
int x1 = point2.getX();
int y1 = point2.getY();
private void plot(PixelWriter pixelWriter, int x, int y, double brightness) {
if (x >= 0 && y >= 0 && x < canvas.getWidth() && y < canvas.getHeight()) {
// Ограничиваем яркость в диапазоне от 0 до 1
brightness = Math.max(0, Math.min(1, brightness));
Color color = new Color(0, 0, 0, brightness);
pixelWriter.setColor(x, y, color);
}
}
Assistant
User
Connected to the target VM, address: '127.0.0.1:51866', transport: 'socket'
Exception in thread "main" java.lang.IllegalAccessError: class org.junit.platform.engine.UniqueId (in unnamed module @0xea1a8d5) cannot access class org.junit.platform.commons.util.Preconditions (in module org.junit.platform.commons) because module org.junit.platform.commons does not export org.junit.platform.commons.util to unnamed module @0xea1a8d5
at org.junit.platform.engine.UniqueId.forEngine(UniqueId.java:68)
at com.intellij.junit5.JUnit5IdeaTestRunner.(JUnit5IdeaTestRunner.java:72)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:413)
at java.base/java.lang.Class.forName(Class.java:404)
at com.intellij.rt.junit.JUnitStarter.getAgentClass(JUnitStarter.java:241)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:222)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:55)
Disconnected from the target VM, address: '127.0.0.1:51866', transport: 'socket'
Assistant
The IllegalAccessError you're encountering indicates a problem with module accessibility in your JUnit test execution configuration. Specifically, the test class or the testing framework cannot access internal classes due to module encapsulation in the Java 9+ module system.
private void drawBresenhamLine(GraphicsContext graphicsContext, Point point1, Point point2) {
int x0 = point1.getX();
int y0 = point1.getY();
int x1 = point2.getX();
int y1 = point2.getY();
int dx = Math.abs(x1 - x0);
int dy = Math.abs(y1 - y0);
int sx = x0 < x1 ? 1 : -1;
int sy = y0 < y1 ? 1 : -1;
int err = dx - dy;
WritableImage writableImage = new WritableImage((int) canvas.getWidth(), (int) canvas.getHeight());
PixelWriter pixelWriter = writableImage.getPixelWriter();
while (true) {
pixelWriter.setColor(x0, y0, Color.BLACK);
if (x0 == x1 && y0 == y1)
break;
int e2 = 2 * err;
if (e2 > -dy) {
err -= dy;
x0 += sx;
}
if (e2 < dx) {
err += dx;
y0 += sy;
}
}
graphicsContext.drawImage(writableImage, 0, 0);
}
private void drawDDALine(GraphicsContext graphicsContext, Point point1, Point point2) {
double dx = point2.getX() - point1.getX();
double dy = point2.getY() - point1.getY();
final double step;
if (Math.abs(dx) > Math.abs(dy)) {
step = Math.abs(dx);
} else {
step = Math.abs(dy);
}
dy /= step;
dx /= step;
double x = point1.getX();
double y = point1.getY();
WritableImage writableImage = new WritableImage((int) canvas.getWidth(), (int) canvas.getHeight());
PixelWriter pixelWriter = writableImage.getPixelWriter();
for (int i = 0; i < step; i++) {
pixelWriter.setColor((int) x, (int) y, Color.BLACK);
x = x + dx;
y = y + dy;
}
graphicsContext.drawImage(writableImage, 0, 0);
private static void fillScanline(
PixelWriter pixelWriter,
int x,
int y,
Point center,
Color centerColor,
Color edgeColor,
double focusA,
double focusB) {
int startX = (int) (center.getX() - x);
int endX = (int) (center.getX() + x);
int y1 = (int) (center.getY() + y);
int y2 = (int) (center.getY() - y);
for (int xi = startX; xi <= endX; xi++) {
interpolateAndSetColor(pixelWriter, xi, y1, center, centerColor, edgeColor, focusA, focusB);
interpolateAndSetColor(pixelWriter, xi, y2, center, centerColor, edgeColor, focusA, focusB);
}
}
private static void interpolateAndSetColor(
PixelWriter pixelWriter,
int x,
int y,
Point center,
Color centerColor,
Color edgeColor,
double focusA,
double focusB) {
// Вычисляем нормализованное расстояние от центра
double dx = x - center.getX();
double dy = y - center.getY();
double distance = Math.sqrt(dx * dx + dy * dy);
double maxDistance = Math.sqrt(focusA * focusA + focusB * focusB);
// t между 0 и 1
double t = Math.min(distance / maxDistance, 1.0);
// интерполяция цвета
double red = (1 - t) * centerColor.getRed() + t * edgeColor.getRed();
double green = (1 - t) * centerColor.getGreen() + t * edgeColor.getGreen();
double blue = (1 - t) * centerColor.getBlue() + t * edgeColor.getBlue();
double opacity = (1 - t) * centerColor.getOpacity() + t * edgeColor.getOpacity();
// цвета должны быть в диапозоне [0,1]
red = Math.max(0, Math.min(red, 1));
green = Math.max(0, Math.min(green, 1));
blue = Math.max(0, Math.min(blue, 1));
opacity = Math.max(0, Math.min(opacity, 1));
Color color = new Color(red, green, blue, opacity);
pixelWriter.setColor(x, y, color);
}
protected static void drawOvalByInterpolate(
GraphicsContext graphicsContext,
int x, int y,
final int width, final int height,
final Color centerColor,
final Color edgeColor, Canvas canvas) {
WritableImage writableImage = new WritableImage(
(int) canvas.getWidth(),
(int) canvas.getHeight());
PixelWriter pixelWriter = writableImage.getPixelWriter();
int focusA = width / 2;
int focusB = height / 2;
Point center = new Point(x + focusA, y + focusB);
int xi = 0;
int yi = focusB;
double a2 = focusA * focusA;
double b2 = focusB * focusB;
// Decision parameters
double d1 = b2 - a2 * focusB + 0.25 * a2;
double dx = 2 * b2 * xi;
double dy = 2 * a2 * yi;
// Region 1
while (dx < dy) {
fillScanline(pixelWriter, xi, yi, center, centerColor, edgeColor, focusA, focusB);
if (d1 < 0) {
xi++;
dx += 2 * b2;
d1 += dx + b2;
} else {
xi++;
yi--;
dx += 2 * b2;
dy -= 2 * a2;
d1 += dx - dy + b2;
}
}
// Region 2
double d2 = b2 * (xi + 0.5) * (xi + 0.5) + a2 * (yi - 1) * (yi - 1) - a2 * b2;
while (yi >= 0) {
fillScanline(pixelWriter, xi, yi, center, centerColor, edgeColor, focusA, focusB);
if (d2 > 0) {
yi--;
dy -= 2 * a2;
d2 += a2 - dy;
} else {
xi++;
yi--;
dx += 2 * b2;
dy -= 2 * a2;
d2 += dx - dy + a2;
}
}
graphicsContext.drawImage(writableImage, 0, 0);
}
}
package com.cgvsu.rasterizationfxapp.figure;
import javafx.beans.NamedArg;
public class Point {
private int x;
private int y;
public Point(@NamedArg("x") int x, @NamedArg("y") int y) {
this.x = x;
this.y = y;
}
public class Rasterization {
private static Canvas canvas;
public static void drawRectangle(
final GraphicsContext graphicsContext,
final int x, final int y,
final int width, final int height,
final Color color) {
final PixelWriter pixelWriter = graphicsContext.getPixelWriter();
for (int row = y; row < y + height; ++row) {
for (int col = x; col < x + width; ++col) {
pixelWriter.setColor(col, row, color);
}
}
}
public static void drawOval(
GraphicsContext graphicsContext,
int x, int y,
final int width, final int height,
final Color centerColor,
final Color edgeColor) {
drawOvalByInterpolate(graphicsContext, x, y, width, height, centerColor, edgeColor, canvas);
}
public class RasterizationApplication extends Application {
@Override
public void start(Stage stage) throws IOException {
FXMLLoader fxmlLoader = new FXMLLoader(RasterizationApplication.class.getResource("mainwindow.fxml"));
Scene scene = new Scene(fxmlLoader.load(), 800, 600);
stage.setTitle("Rasterization App");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}package com.cgvsu.rasterizationfxapp;
private void handlePrimaryClick(GraphicsContext graphicsContext, MouseEvent event) {
DrawLine draw = new DrawLine();
draw.setCanvas(canvas);
final Point clickPoint = new Point((int) event.getX(), (int) event.getY());
if (!points.isEmpty()) {
final Point lastPoint = points.get(points.size() - 1);
draw.drawLine(graphicsContext, lastPoint, clickPoint, 1);
}
points.add(clickPoint);
}
} соблюдены ли принципы ооп, сделай юнит тесты
Analyzing your JavaFX code, I can provide insights into the OOP principles and how you might create unit tests for the DrawLine, Oval, Point, and Rasterization classes.
Object-Oriented Principles:
Encapsulation:
Classes like DrawLine, Oval, Rasterization, and Point encapsulate functionality that is specific to drawing operations. Fields in these classes are mostly private, which is good practice. Methods are used to interact with the class state, providing control over how the data is accessed or modified.
Abstraction:
Abstraction is achieved through methods that represent higher-level operations (e.g., drawLine, drawOvalByInterpolate) instead of exposing the complex logic within those methods directly.
Inheritance and Polymorphism:
Your code does not explicitly use inheritance or polymorphism. This is common in such applications, as the focus is more on procedure (drawing shapes) rather than extending functionality through subclasses. However, if you plan to extend functionality in the future, consider an interface or abstract class for drawable objects.
Single Responsibility Principle:
Each class seems to have a single responsibility, which is good. For instance, DrawLine is responsible for line drawing operations, Oval handles oval drawing, and Point represents a coordinate point.
Unit Tests:
To write unit tests, you typically use a testing framework like JUnit. Since your classes rely on JavaFX components (e.g., Canvas, GraphicsContext), testing graphical output can be challenging. However, you can test the non-GUI logic in isolation.
Here's an example structure for testing the Point class with JUnit:
Adding JUnit as a Dependency:
If you haven't already, add JUnit to your project. For a Maven project, the dependency in your pom.xml would look like this:
import org.junit.Assert;
import org.junit.Test;
import com.cgvsu.rasterizationfxapp.figure.Point;
public class PointTest {
@Test
public void testDistance() {
Point point = new Point(3, 4);
Assert.assertEquals(5.0, point.distance(0, 0), 0.01);
}
}
Considerations for GUI-Based Tests:
For visually testing or verifying the GUI output, you may need a testing library that supports JavaFX, like TestFX.
Alternatively, consider refactoring your code to separate drawing logic (which can be tested) from actual rendering, allowing you to test logical calculations outside the GUI context.
Start by testing the non-GUI parts of your application (like the Point class's methods). For GUI rendering, reviewing the output visually is also a practical approach, especially if your application involves complex graphical operations that are challenging to validate programmatically. If you plan to expand this app, consider setting up a structure that allows more testable code by abstracting logic away from GUI operations.
Here's how you can address this problem:
Solutions:
Check JUnit Version:
Ensure that you are using compatible versions of JUnit and other related testing libraries. If you're using JUnit 5, ensure you have the following dependencies (example for Maven):
Make sure that org.junit.platform.commons is correctly set up and compatible with your JUnit version.
Module System Configuration:
If you're using the Java module system (e.g., with module-info.java), ensure that necessary modules are correctly required and that exports are properly specified. You might need to open your module for test execution:
open module your.module.name {
requires org.junit.jupiter.api;
requires org.junit.platform.commons;
}
Update IntelliJ IDEA:
Ensure your IntelliJ IDEA is up to date, as some older versions might have issues with running JUnit 5 tests.
Check IDE Test Configuration:
Go to Run > Edit Configurations in IntelliJ IDEA, select your JUnit test configuration, and ensure the test scope and classpath settings are appropriate.
Re-import the Project:
If using IntelliJ IDEA, you can try refreshing your project by going to File > Invalidate Caches / Restart, then re-import your project. This can sometimes resolve classpath or configuration issues.
Switch Execution Environment:
As a workaround, if you're running into persistent issues with a specific version of Java, consider testing in a different environment (e.g., a newer JDK version or removing the module-info.java file if not needed).
Implement one or a combination of these solutions based on your project's specific setup. If the issue persists, checking the exact library versions and settings might be necessary to pinpoint the cause accurately.
Ваш module-info.java файл обеспечивает основные зависимости и экспорт/открытие пакетов вашего приложения для работы с JavaFX и тестовыми библиотеками. Вот обновлённый вариант с пояснениями и улучшениями:
module com.cgvsu.rasterizationfxapp {
requires javafx.controls;
requires javafx.fxml;
requires java.desktop; // Это требуется для работы с графическими компонентами AWT/Swing
// Удалите org.testng, если вы намерены использовать только JUnit для тестирования.
requires org.junit.jupiter.api; // JUnit для модульного тестирования
// Открывает ваш основной пакет для JavaFX
opens com.cgvsu.rasterizationfxapp to javafx.fxml;
// Экспортирует ваш основной пакет, чтобы другие модули могли его использовать, если нужно
exports com.cgvsu.rasterizationfxapp;
// Экспортирует фигуры, если они используются извне
exports com.cgvsu.rasterizationfxapp.figure;
// Делает фигуры доступными для fxml и в то же время для JavaFX сценариума
opens com.cgvsu.rasterizationfxapp.figure to javafx.fxml;
// Если вам нужно, чтобы тесты из org.junit.jupiter.api имели доступ к приватным элементам,
// Вы можете также добавить что-то вроде:
// opens com.cgvsu.rasterizationfxapp to org.junit.platform.commons;
}
Замечания:
Тестовые зависимости:
Убедитесь, что org.junit.jupiter.api используется вместо org.testng для тестирования, если вы не используете TestNG. Если планируете использовать TestNG, настройте помимо JUnit соответствующие зависимости.
Экспорт и открытие:
Использование opens позволяет JavaFX и другим модулям рефлексивный доступ к внутренним частям модуля. Это необходимо для того, чтобы JavaFX мог корректно загружать ваши классы и fxml-файлы.
Доступность классов:
Экспорт пакета (exports) нужен для того, чтобы другие модули могли использовать публичные классы и интерфейсы. Если не предполагается использование вашего приложения в качестве библиотеки, исходящие экспортные операторы могут быть минимальны.
Если у вас нет особых причин для использования java.desktop, и вы работаете только с JavaFX, иногда можно обойтись без этого требования, но это зависит от того, что требует ваш проект. Если вы добавляете другие тестовые библиотеки, убедитесь, что они правильно настроены в вашем build.gradle или pom.xml.
Если у вас возникают сложности при выполнении тестов, убедитесь в правильности сборки проекта и настройки окружения в вашей IDE. Наконец, всегда проверяйте, что используете совместимые версии всех библиотек и плагинов.