Java awt windows thread

Руководство по Java AWT

Если мы говорим о программировании GUI, Java предоставляет богатый набор библиотек для разработки высокоинтерактивных графических интерфейсов, заключенных в AWT API. В этом уроке по Java AWT я кратко ознакомлю вас с его компонентами.

Ниже приведены темы, рассматриваемые в этом руководстве:

  • Что такое Java AWT?
  • Особенности
  • Аспекты
  • Иерархия
  • Компоненты
  • Разработка калькулятора с помощью Java AWT

Что такое AWT в Java?

Abstract Window Toolkit (AWT) – это инструментарий классов в Java, который помогает программисту разрабатывать компоненты графического и графического интерфейса пользователя. Он является частью JFC (Java Foundation Classes), разработанной Sun Microsystems.

AWT API в Java в основном состоит из полного набора классов и методов, которые необходимы для упрощенного создания и управления графическим интерфейсом пользователя (GUI). Он был разработан для предоставления общего набора инструментов для проектирования кроссплатформенных графических интерфейсов.

Одной из важных особенностей AWT является то, что он зависит от платформы. Это означает, что инструменты AWT используют нативные наборы инструментов платформ, которые они внедряют.

Этот подход помогает сохранить внешний вид каждой платформы. Но, как уже говорилось, все идет с ценой, у этого подхода есть существенный недостаток. При выполнении на разных платформах из-за зависимости платформы она будет выглядеть по-разному на каждой платформе. Это затрудняет согласованность и эстетику приложения.

Особенности AWT в Java

  • AWT – это набор компонентов собственного интерфейса пользователя.
  • Он основан на надежной модели обработки событий
  • Он предоставляет графические и графические инструменты, такие как формы, цвета и классы шрифтов.
  • AWT также использует менеджеры по расположению, которые помогают в увеличении гибкости расположения окон
  • Классы передачи данных также являются частью AWT, которая помогает вырезать и вставлять через родной буфер обмена платформы
  • Поддерживает широкий спектр библиотек, необходимых для создания графики для игровых продуктов, банковских услуг, образовательных целей и т. д.

AWT UI Аспекты

Любой пользовательский интерфейс будет состоять из трех объектов:

  • Элементы пользовательского интерфейса: они относятся к основным визуальным элементам, которые видны пользователю и используются для взаимодействия с приложением. AWT в Java предоставляет полный список широко используемых и распространенных элементов.
  • Макеты: они определяют, как элементы пользовательского интерфейса будут организованы на экране, и обеспечивают окончательный внешний вид графического интерфейса.
  • Поведение: они определяют события, которые должны происходить, когда пользователь взаимодействует с элементами пользовательского интерфейса.

Иерархия

Ниже я показал общее описание класса java.awt.Component:

AWT Компоненты

1. Контейнеры

Контейнер в Java AWT – это компонент, который используется для хранения других компонентов, таких как текстовые поля, кнопки и т. д. Он является подклассом java.awt.Component и отвечает за отслеживание добавляемых компонентов. AWT в Java предоставляет четыре типа контейнеров.

Типы Контейнеров

2. Кнопка

Класс java.awt.Button используется для создания помеченной кнопки. Компонент графического интерфейса, который запускает определенный запрограммированный при нажатии на него. Класс Button имеет два конструктора:

Несколько методов, предоставляемых этим классом, перечислены ниже:

3. Текстовое поле

Класс java.awt.TextField создает однострочное текстовое поле для ввода текста пользователями. Класс TextField имеет три конструктора:

Читайте также:  Установка контейнера docker windows

Вот несколько методов, предоставляемых классом TextField:

4. Метка

Класс java.awt.Label предоставляет текстовую строку с описанием, видимую в графическом интерфейсе. Объект метки AWT – это компонент для размещения текста в контейнере. Класс Label имеет три конструктора:

Этот класс также предоставляет 3 константы:

Ниже я перечислил открытые методы, предоставляемые этим классом:

5. Холст

Класс Canvas представляет прямоугольную область, в которой вы можете рисовать в приложении или получать входные данные, созданные пользователем.

6. Выбор

Класс выбора используется для представления всплывающего меню выбора. Выбранный вариант отображается в верхней части данного меню.

7. Полоса прокрутки

Объект класса Scrollbar используется для добавления горизонтальной и вертикальной полосы прокрутки в GUI. Это позволяет пользователю видеть невидимое количество строк и столбцов.

8. Список

Объект класса List представляет собой список текстовых элементов. Используя класс List, пользователь может выбрать либо один элемент, либо несколько элементов.

9. CheckBox

Флажок представляет собой класс графического компонента, который используется для создания флажка. У него есть два варианта состояния; правда и ложь. В любой момент времени он может иметь любой из двух.

Разработка калькулятора с помощью Java AWT

Здесь я покажу вам, как создать калькулятор с помощью AWT, где вы сможете выполнять основные математические операции. Ниже приведен скриншот того, как будет выглядеть ваш калькулятор.

Теперь, чтобы построить это, вам нужно ввести следующий код:

Как вы могли заметить, здесь мы использовали только функциональные возможности. Вы всегда можете добавить больше функций в свое приложение и создать полноценный калькулятор.

Java awt windows thread

A window must have either a frame, dialog, or another window defined as its owner when it’s constructed.

In a multi-screen environment, you can create a Window on a different screen device by constructing the Window with Window(Window, GraphicsConfiguration) . The GraphicsConfiguration object is one of the GraphicsConfiguration objects of the target screen device.

In a virtual device multi-screen environment in which the desktop area could span multiple physical screen devices, the bounds of all configurations are relative to the virtual device coordinate system. The origin of the virtual-coordinate system is at the upper left-hand corner of the primary physical screen. Depending on the location of the primary screen in the virtual device, negative coordinates are possible, as shown in the following figure.

In such an environment, when calling setLocation , you must pass a virtual coordinate to this method. Similarly, calling getLocationOnScreen on a Window returns virtual device coordinates. Call the getBounds method of a GraphicsConfiguration to find its origin in the virtual coordinate system.

The following code sets the location of a Window at (10, 10) relative to the origin of the physical screen of the corresponding GraphicsConfiguration . If the bounds of the GraphicsConfiguration is not taken into account, the Window location would be set at (10, 10) relative to the virtual-coordinate system and would appear on the primary physical screen, which might be different from the physical screen of the specified GraphicsConfiguration .

Note: the location and size of top-level windows (including Window s, Frame s, and Dialog s) are under the control of the desktop’s window management system. Calls to setLocation , setSize , and setBounds are requests (not directives) which are forwarded to the window management system. Every effort will be made to honor such requests. However, in some cases the window management system may ignore such requests, or modify the requested geometry in order to place and size the Window in a way that more closely matches the desktop settings.

Читайте также:  Как добавить виджет windows 10

Due to the asynchronous nature of native event handling, the results returned by getBounds , getLocation , getLocationOnScreen , and getSize might not reflect the actual geometry of the Window on screen until the last request has been processed. During the processing of subsequent requests these values might change accordingly while the window management system fulfills the requests.

An application may set the size and location of an invisible Window arbitrarily, but the window management system may subsequently change its size and/or location when the Window is made visible. One or more ComponentEvent s will be generated to indicate the new geometry.

Windows are capable of generating the following WindowEvents: WindowOpened, WindowClosed, WindowGainedFocus, WindowLostFocus.

Java awt windows thread

A window must have either a frame, dialog, or another window defined as its owner when it’s constructed.

In a multi-screen environment, you can create a Window on a different screen device by constructing the Window with Window(Window, GraphicsConfiguration) . The GraphicsConfiguration object is one of the GraphicsConfiguration objects of the target screen device.

In a virtual device multi-screen environment in which the desktop area could span multiple physical screen devices, the bounds of all configurations are relative to the virtual device coordinate system. The origin of the virtual-coordinate system is at the upper left-hand corner of the primary physical screen. Depending on the location of the primary screen in the virtual device, negative coordinates are possible, as shown in the following figure.

In such an environment, when calling setLocation , you must pass a virtual coordinate to this method. Similarly, calling getLocationOnScreen on a Window returns virtual device coordinates. Call the getBounds method of a GraphicsConfiguration to find its origin in the virtual coordinate system.

The following code sets the location of a Window at (10, 10) relative to the origin of the physical screen of the corresponding GraphicsConfiguration . If the bounds of the GraphicsConfiguration is not taken into account, the Window location would be set at (10, 10) relative to the virtual-coordinate system and would appear on the primary physical screen, which might be different from the physical screen of the specified GraphicsConfiguration .

Note: the location and size of top-level windows (including Window s, Frame s, and Dialog s) are under the control of the desktop’s window management system. Calls to setLocation , setSize , and setBounds are requests (not directives) which are forwarded to the window management system. Every effort will be made to honor such requests. However, in some cases the window management system may ignore such requests, or modify the requested geometry in order to place and size the Window in a way that more closely matches the desktop settings.

Due to the asynchronous nature of native event handling, the results returned by getBounds , getLocation , getLocationOnScreen , and getSize might not reflect the actual geometry of the Window on screen until the last request has been processed. During the processing of subsequent requests these values might change accordingly while the window management system fulfills the requests.

Читайте также:  Оперативная система windows кратко

An application may set the size and location of an invisible Window arbitrarily, but the window management system may subsequently change its size and/or location when the Window is made visible. One or more ComponentEvent s will be generated to indicate the new geometry.

Windows are capable of generating the following WindowEvents: WindowOpened, WindowClosed, WindowGainedFocus, WindowLostFocus.

Java awt windows thread

A window must have either a frame, dialog, or another window defined as its owner when it’s constructed.

In a multi-screen environment, you can create a Window on a different screen device by constructing the Window with Window(Window, GraphicsConfiguration) . The GraphicsConfiguration object is one of the GraphicsConfiguration objects of the target screen device.

In a virtual device multi-screen environment in which the desktop area could span multiple physical screen devices, the bounds of all configurations are relative to the virtual device coordinate system. The origin of the virtual-coordinate system is at the upper left-hand corner of the primary physical screen. Depending on the location of the primary screen in the virtual device, negative coordinates are possible, as shown in the following figure.

In such an environment, when calling setLocation , you must pass a virtual coordinate to this method. Similarly, calling getLocationOnScreen on a Window returns virtual device coordinates. Call the getBounds method of a GraphicsConfiguration to find its origin in the virtual coordinate system.

The following code sets the location of a Window at (10, 10) relative to the origin of the physical screen of the corresponding GraphicsConfiguration . If the bounds of the GraphicsConfiguration is not taken into account, the Window location would be set at (10, 10) relative to the virtual-coordinate system and would appear on the primary physical screen, which might be different from the physical screen of the specified GraphicsConfiguration .

Note: the location and size of top-level windows (including Window s, Frame s, and Dialog s) are under the control of the desktop’s window management system. Calls to setLocation , setSize , and setBounds are requests (not directives) which are forwarded to the window management system. Every effort will be made to honor such requests. However, in some cases the window management system may ignore such requests, or modify the requested geometry in order to place and size the Window in a way that more closely matches the desktop settings.

Due to the asynchronous nature of native event handling, the results returned by getBounds , getLocation , getLocationOnScreen , and getSize might not reflect the actual geometry of the Window on screen until the last request has been processed. During the processing of subsequent requests these values might change accordingly while the window management system fulfills the requests.

An application may set the size and location of an invisible Window arbitrarily, but the window management system may subsequently change its size and/or location when the Window is made visible. One or more ComponentEvent s will be generated to indicate the new geometry.

Windows are capable of generating the following WindowEvents: WindowOpened, WindowClosed, WindowGainedFocus, WindowLostFocus.

Оцените статью