Интерфейс AWT Native для Java: Прямой доступ к графике из нативного кода
Java AWT Native Interface
Java AWT Native Interface (JAWT): прямой рендеринг в Java из нативного кода. Ускоряет 3D-графику, математические вычисления и работу с AWT Canvas. JNI, производительность.
Сравнивайте с английским: нажмите на абзац — оригинал откроется в окне. Кнопка EN под абзацем показывает его прямо в тексте.
Содержание
Введение
Java AWT Native Interface (JAWT) – это интерфейс для языка программирования Java, который позволяет библиотекам рендеринга, скомпилированным в нативный код, рисовать непосредственно на поверхности рисования объектов Java Abstract Window Toolkit (AWT). Java Native Interface (JNI) позволяет разработчикам добавлять платформенно-зависимую функциональность в приложения Java. JNI позволяет разработчикам добавлять критически важные по времени операции, такие как математические вычисления и 3D-рендеринг. Ранее нативный 3D-рендеринг был сложной задачей, поскольку нативный код не имел доступа к графическому контексту. AWT Native Interface разработан для предоставления разработчикам доступа к AWT Canvas для непосредственного рисования с использованием нативного кода. Фактически, расширение Java 3D API к стандартному Java SE JDK в значительной степени опирается на AWT Native Interface для рендеринга 3D-объектов в Java. AWT Native Interface очень похож на JNI, и этапы его использования аналогичны этапам JNI. Подробное описание техник JNI, используемых AWT Native Interface, можно найти в статье Java Native Interface. AWT Native Interface был добавлен в платформу Java с версией J2SE 1.3 ("Kestrel").
Java AWT Native Interface (JAWT) is an interface for the Java programming language that enables rendering libraries compiled to native code to draw directly to a Java Abstract Window Toolkit (AWT) object drawing surface. The Java Native Interface (JNI) allows developers to add platform dependent functionality to Java applications. The JNI enables developers to add time critical operations like mathematical calculations and 3D rendering. Previously, native 3D rendering was challenging because the native code did not have access to the graphic context. The AWT Native Interface is designed to give developers access to an AWT Canvas for direct drawing with native code. In fact, the Java 3D API extension to the standard Java SE JDK relies heavily on the AWT Native Interface to render 3D objects in Java. The AWT Native Interface is very similar to the JNI and the steps are the same as those of the JNI. See the Java Native Interface article for an explanation of the JNI techniques employed by the AWT Native Interface. The AWT Native Interface was added to the Java platform with the J2SE 1.3 ("Kestrel") version.
Шаги нативной интерфейса AWT
Полный пример использования этой технологии доступен на ВикиКнигах (см. ссылку ниже). Подробный пример, демонстрирующий эту технологию, также доступен на ВикиКнигах (см. ссылку ниже). Для начала создается Java-приложение. В статье объясняется использование Java Native Interface. Ключевое слово `native` и метод `loadLibrary` являются неотъемлемыми компонентами, а метод `paint` вызывается, когда поток диспетчеризации событий AWT перерисовывает экран. После создания Java-приложения обычно генерируется заголовочный файл C++. Подробные объяснения можно найти в документации Java Native Interface. Далее, нативный код C++ реализуется, как правило, в файле с именем "NativeSideCanvas.cpp", и компилируется в библиотеку. Дополнительная информация об этом процессе приведена в документации Java Native Interface (JNI). После сборки программы её можно запустить как обычно. При запуске файла должно появиться окно, отображающее, например, нарисованный прямоугольник. Подробные инструкции можно найти в документации Java Native Interface. Важно отметить, что AWT Native Interface требует наличия файла "jawt.dll" (или "jawt.so") для работы вместе с приложением. Самый простой способ обеспечить это – скопировать файл "jawt.dll", который обычно находится в каталоге /jre/bin в пути установки JDK.
A complete walkthrough example of this technology is available on Wikibooks (see link below). A comprehensive example demonstrating this technology is available on Wikibooks (refer to the link below). To begin, a Java application is created. The utilization of the Java Native Interface is explained in the article. The native keyword and the loadLibrary method are integral components, while the paint method is invoked when the AWT event dispatching thread repaints the screen. Following the creation of the Java application, a C++ header file is generated conventionally. Detailed explanations can be found in the Java Native Interface documentation. Next, the C++ native code is implemented, typically in a file named "NativeSideCanvas. cpp," and compiled into a library. Further information on this process is provided in the Java Native Interface (JNI) documentation. Once the program is constructed, it can be executed as per usual. Upon running the file, a window should appear, displaying, for example, a drawn rectangle. Detailed instructions can be found in the Java Native Interface documentation. It's important to note that the AWT Native Interface necessitates the presence of the "jawt. dll" (or "jawt. so") file to run alongside the application. The simplest method to ensure this is by copying the "jawt. dll" file, typically found in the /jre/bin directory within the JDK's installation path.
Местная живопись
Можно рисовать, как будто это родное приложение. В Windows, JVM передаст HWND и другую информацию об окне в родное приложение, чтобы оно "знало", куда рисовать. Оно может использовать GDI для отрисовки прямоугольника. Информация об окне, необходимая родной стороне, будет содержаться в структуре JAWT Win32DrawingSurfaceInfo (в зависимости от операционной системы), которую можно получить следующей строкой:
One can paint as if it is a native application. In Windows, the JVM will pass a HWND and other window information to the native application so that the application will "know" where to draw. It could use GDI to draw a Rectangle. The window information the native side needs will be in a JAWT Win32DrawingSurfaceInfo structure (depending on Operating System) which can be retrieved with this line: