Учебники

AWT Краткое руководство

Графический интерфейс пользователя (GUI) предлагает взаимодействие с пользователем через некоторые графические компоненты. Например, наша базовая операционная система также предлагает графический интерфейс пользователя через окно, фрейм, панель, кнопку, текстовое поле, TextArea, список, комбинированный список, метку, флажок и т. Д. Все они известны как компоненты. Используя эти компоненты, мы можем создать интерактивный пользовательский интерфейс для приложения.

GUI предоставляет результат конечному пользователю в ответ на вызванные события. GUI полностью основан на событиях. Например, нажатие на кнопку, закрытие окна, открытие окна, ввод чего-либо в текстовой области и т. Д. Эти действия известны как события. Интерфейс пользователя облегчает использование приложения конечным пользователем. Это также делает их интересными.

Основные термины

Срок Описание
Составная часть Компонент – это объект, имеющий графическое представление, которое может отображаться на экране и которое может взаимодействовать с пользователем. Для примеров кнопки, флажки, список и полосы прокрутки графического интерфейса пользователя.

Контейнер Контейнерный объект – это компонент, который может содержать другие компоненты. Компоненты, добавленные в контейнер, отслеживаются в списке. Порядок в списке будет определять порядок размещения компонентов между контейнерами внутри контейнера. Если при добавлении компонента в контейнер индекс не указан, он будет добавлен в конец списка.

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

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

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

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

Примеры приложений на основе графического интерфейса

Ниже приведены некоторые примеры приложений на основе графического интерфейса.

  • Банкомат (банкомат)

  • Система продажи авиабилетов

  • Информационные киоски на вокзалах

  • Мобильные приложения

  • Навигационные системы

Банкомат (банкомат)

Система продажи авиабилетов

Информационные киоски на вокзалах

Мобильные приложения

Навигационные системы

Преимущества GUI перед CUI

  • GUI предоставляет графические значки для взаимодействия, в то время как CUI (Character User Interface) предлагает простые текстовые интерфейсы.

  • GUI делает приложение более интересным и интересным, а CUI – нет.

  • GUI предлагает среду щелчка и выполнения, в то время как в CUI мы каждый раз вводим команду для задачи.

  • Новый пользователь может легко взаимодействовать с графическим интерфейсом пользователя с помощью визуальных индикаторов, но это сложно в пользовательском интерфейсе персонажа.

  • GUI предлагает множество элементов управления файловой системой и операционной системой, в то время как в CUI вы должны использовать команды, которые трудно запомнить.

  • Концепция Windows в GUI позволяет пользователю просматривать, манипулировать и контролировать несколько приложений одновременно, в то время как в CUI пользователь может контролировать одну задачу за раз.

  • GUI обеспечивает многозадачную среду, как и CUI, но CUI не обеспечивает такой же простоты, как GUI.

  • С помощью графического интерфейса проще управлять операционной системой и перемещаться по ней, которая становится очень медленной в командном пользовательском интерфейсе. GUI может быть легко настроен.

GUI предоставляет графические значки для взаимодействия, в то время как CUI (Character User Interface) предлагает простые текстовые интерфейсы.

GUI делает приложение более интересным и интересным, а CUI – нет.

GUI предлагает среду щелчка и выполнения, в то время как в CUI мы каждый раз вводим команду для задачи.

Новый пользователь может легко взаимодействовать с графическим интерфейсом пользователя с помощью визуальных индикаторов, но это сложно в пользовательском интерфейсе персонажа.

GUI предлагает множество элементов управления файловой системой и операционной системой, в то время как в CUI вы должны использовать команды, которые трудно запомнить.

Концепция Windows в GUI позволяет пользователю просматривать, манипулировать и контролировать несколько приложений одновременно, в то время как в CUI пользователь может контролировать одну задачу за раз.

GUI обеспечивает многозадачную среду, как и CUI, но CUI не обеспечивает такой же простоты, как GUI.

С помощью графического интерфейса проще управлять операционной системой и перемещаться по ней, которая становится очень медленной в командном пользовательском интерфейсе. GUI может быть легко настроен.

Настройка среды

В этом разделе рассказывается, как загрузить и настроить Java на вашем компьютере. Пожалуйста, выполните следующие шаги для настройки среды.

Java SE находится в свободном доступе по ссылке Скачать Java . Таким образом, вы загружаете версию, основанную на вашей операционной системе.

Следуйте инструкциям для загрузки Java и запуска .exe для установки Java на вашем компьютере. После того, как вы установили Java на свой компьютер, вам нужно будет установить переменные окружения, чтобы они указывали на правильные каталоги установки:

Настройка пути для Windows 2000 / XP:

Предполагая, что вы установили Java в каталог c: \ Program Files \ java \ jdk :

  • Щелкните правой кнопкой мыши «Мой компьютер» и выберите «Свойства».

  • Нажмите кнопку «Переменные среды» на вкладке «Дополнительно».

  • Теперь измените переменную Path, чтобы она также содержала путь к исполняемому файлу Java. Например, если в настоящий момент путь задан как «C: \ WINDOWS \ SYSTEM32», измените ваш путь на «C: \ WINDOWS \ SYSTEM32; c: \ Program Files \ java \ jdk \ bin».

Щелкните правой кнопкой мыши «Мой компьютер» и выберите «Свойства».

Нажмите кнопку «Переменные среды» на вкладке «Дополнительно».

Теперь измените переменную Path, чтобы она также содержала путь к исполняемому файлу Java. Например, если в настоящий момент путь задан как «C: \ WINDOWS \ SYSTEM32», измените ваш путь на «C: \ WINDOWS \ SYSTEM32; c: \ Program Files \ java \ jdk \ bin».

Настройка пути для Windows 95/98 / ME:

Предполагая, что вы установили Java в каталог c: \ Program Files \ java \ jdk :

  • Отредактируйте файл ‘C: \ autoexec.bat’ и добавьте следующую строку в конце:

    ‘SET PATH =% PATH%; C: \ Program Files \ java \ jdk \ bin’

Отредактируйте файл ‘C: \ autoexec.bat’ и добавьте следующую строку в конце:

‘SET PATH =% PATH%; C: \ Program Files \ java \ jdk \ bin’

Настройка пути для Linux, UNIX, Solaris, FreeBSD:

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

Например, если вы используете bash в качестве оболочки, вы добавили бы следующую строку в конец вашего .bashrc: export PATH = / path / to / java: $ PATH ‘

Популярные редакторы Java:

Для написания ваших Java-программ вам понадобится текстовый редактор. На рынке доступны еще более сложные IDE. Но сейчас вы можете рассмотреть один из следующих:

  • Блокнот: на компьютере с Windows вы можете использовать любой простой текстовый редактор, например Блокнот (рекомендуется для этого урока), TextPad.

  • Netbeans: Java IDE с открытым исходным кодом, который можно бесплатно загрузить по адресу http://www.netbeans.org/index.html .

  • Eclipse: также является Java IDE, разработанной сообществом открытого исходного кода eclipse и может быть загружена с http://www.eclipse.org/ .

Блокнот: на компьютере с Windows вы можете использовать любой простой текстовый редактор, например Блокнот (рекомендуется для этого урока), TextPad.

Netbeans: Java IDE с открытым исходным кодом, который можно бесплатно загрузить по адресу http://www.netbeans.org/index.html .

Eclipse: также является Java IDE, разработанной сообществом открытого исходного кода eclipse и может быть загружена с http://www.eclipse.org/ .

AWT Controls

Каждый пользовательский интерфейс рассматривает следующие три основных аспекта:

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

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

  • Поведение: это события, которые происходят, когда пользователь взаимодействует с элементами пользовательского интерфейса. Эта часть будет рассмотрена в главе «Обработка событий».

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

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

Поведение: это события, которые происходят, когда пользователь взаимодействует с элементами пользовательского интерфейса. Эта часть будет рассмотрена в главе «Обработка событий».

UI классы

Каждый элемент управления AWT наследует свойства от класса Component.

Класс компонентов AWT

Вступление

Класс Component является абстрактным базовым классом для элементов управления пользовательского интерфейса без меню AWT. Компонент представляет объект с графическим представлением.

Объявление класса

Ниже приводится объявление для класса java.awt.Component :

public abstract class Component
   extends Object
      implements ImageObserver, MenuContainer, Serializable

поле

Ниже приведены поля для класса java.awt.Component :

  • static float BOTTOM_ALIGNMENT – Константа простоты использования для getAlignmentY.

  • static float CENTER_ALIGNMENT – Константа простоты использования для getAlignmentY и getAlignmentX.

  • static float LEFT_ALIGNMENT – Константа простоты использования для getAlignmentX.

  • static float RIGHT_ALIGNMENT – Константа простоты использования для getAlignmentX.

  • static float TOP_ALIGNMENT – Константа простоты использования для getAlignmentY ().

static float BOTTOM_ALIGNMENT – Константа простоты использования для getAlignmentY.

static float CENTER_ALIGNMENT – Константа простоты использования для getAlignmentY и getAlignmentX.

static float LEFT_ALIGNMENT – Константа простоты использования для getAlignmentX.

static float RIGHT_ALIGNMENT – Константа простоты использования для getAlignmentX.

static float TOP_ALIGNMENT – Константа простоты использования для getAlignmentY ().

Конструкторы классов

SN Конструктор и описание
1

защищенный компонент ()

Это создает новый компонент.

защищенный компонент ()

Это создает новый компонент.

Методы класса

SN Метод и описание
1

логическое действие (событие evt, объект чего)

Устаревшее. Начиная с версии 1.1 JDK, этот компонент должен регистрироваться как ActionListener для компонента, который запускает события действия.

2

void add (PopupMenu popup)

Добавляет указанное всплывающее меню к компоненту.

3

void addComponentListener (ComponentListener l)

Добавляет указанный слушатель компонента для получения событий компонента от этого компонента.

4

void addFocusListener (FocusListener l)

Добавляет указанный слушатель фокуса для получения событий фокуса от этого компонента, когда этот компонент получает фокус ввода.

5

void addHierarchyBoundsListener (HierarchyBoundsListener l)

Добавляет указанный прослушиватель границ иерархии для получения событий границ иерархии от этого компонента, когда изменяется иерархия, к которой принадлежит этот контейнер.

6

void addHierarchyListener (HierarchyListener l)

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

7

void addInputMethodListener (InputMethodListener l)

Добавляет указанный прослушиватель метода ввода для получения событий метода ввода от этого компонента.

8

void addKeyListener (KeyListener l)

Добавляет указанный ключевой слушатель, чтобы получить ключевые события от этого компонента.

9

void addMouseListener (MouseListener l)

Добавляет указанный слушатель мыши для получения событий мыши от этого компонента.

10

void addMouseMotionListener (MouseMotionListener l)

Добавляет указанный слушатель движения мыши, чтобы получать события движения мыши от этого компонента.

11

void addMouseWheelListener (MouseWheelListener l)

Добавляет указанный слушатель колеса мыши для получения событий колеса мыши от этого компонента.

12

void addNotify ()

Делает этот компонент отображаемым, подключая его к собственному экранному ресурсу.

13

void addPropertyChangeListener (слушатель PropertyChangeListener)

Добавляет PropertyChangeListener в список слушателей.

14

void addPropertyChangeListener (String propertyName, прослушиватель PropertyChangeListener)

Добавляет PropertyChangeListener в список слушателей для определенного свойства.

15

void applyComponentOrientation (ориентация компонента)

Устанавливает свойство ComponentOrientation этого компонента и всех компонентов, содержащихся в нем.

16

логическое значение areFocusTraversalKeysSet (int id)

Возвращает, был ли явно задан Набор ключей обхода фокуса для данной операции обхода фокуса для этого Компонента.

17

int checkImage (изображение, обозреватель ImageObserver)

Возвращает статус построения экранного представления указанного изображения.

18

int checkImage (изображение изображения, ширина int, высота int, наблюдатель ImageObserver)

Возвращает статус построения экранного представления указанного изображения.

19

логическое значение содержит (int x, int y)

Проверяет, «содержит» ли этот компонент указанную точку, где x и y определены как относящиеся к системе координат этого компонента.

20

логическое содержит (точка р)

Проверяет, «содержит» ли этот компонент указанную точку, где координаты точки x и y определены как относящиеся к системе координат этого компонента.

21

Image createImage (производитель ImageProducer)

Создает изображение из указанного производителя изображений.

22

Изображение createImage (int width, int height)

Создает закадровое нарисованное изображение, которое будет использоваться для двойной буферизации.

23

VolatileImage createVolatileImage (int width, int height)

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

24

VolatileImage createVolatileImage (int ширина, int высота, ограничения ImageCapabilities)

Создает нестабильное закадровое нарисованное изображение с заданными возможностями.

25

void deliveryEvent (Событие e)

Устаревшее. Начиная с версии 1.1 JDK, заменено на dispatchEvent (AWTEvent e).

26

void disable ()

Устаревшее. Начиная с версии 1.1 JDK, заменено на setEnabled (логическое).

27

Защищенный void disableEvents (long eventsToDisable)

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

28

void dispatchEvent (AWTEvent e)

Отправляет событие этому компоненту или одному из его подкомпонентов.

29

void doLayout ()

Предлагает диспетчеру компоновки выложить этот компонент.

30

void enable ()

Устаревшее. Начиная с версии 1.1 JDK, заменено на setEnabled (логическое).

31

void enable (логическое значение b)

Устаревшее. Начиная с версии 1.1 JDK, заменено на setEnabled (логическое).

32

Защищенный void enableEvents (long eventsToEnable)

Включает события, определенные указанным параметром маски события, для доставки этому компоненту.

33

void enableInputMethods (логическое включение)

Включает или отключает поддержку метода ввода для этого компонента.

34

защищенный void firePropertyChange (строковое propertyName, логическое oldValue, логическое newValue)

Поддержка отчетов об изменениях связанных свойств для логических свойств.

35

void firePropertyChange (String propertyName, байт oldValue, байт newValue)

Сообщает о связанном изменении свойства.

36

void firePropertyChange (String propertyName, char oldValue, char newValue)

Сообщает о связанном изменении свойства.

37

void firePropertyChange (String propertyName, double oldValue, double newValue)

Сообщает о связанном изменении свойства.

38

void firePropertyChange (String propertyName, float oldValue, float newValue)

Сообщает о связанном изменении свойства.

39

void firePropertyChange (String propertyName, long oldValue, long newValue)

Сообщает о связанном изменении свойства.

40

Защищенный void firePropertyChange (String propertyName, Объект oldValue, Объект newValue)

Поддержка отчетов об изменениях связанных свойств для свойств объекта.

41

void firePropertyChange (String propertyName, короткое oldValue, короткое newValue)

Сообщает о связанном изменении свойства.

42

AccessibleContext getAccessibleContext ()

Получает AccessibleContext, связанный с этим Компонентом.

43

float getAlignmentX ()

Возвращает выравнивание по оси x.

44

float getAlignmentY ()

Возвращает выравнивание по оси Y.

45

Цвет getBackground ()

Получает цвет фона этого компонента.

46

int getBaseline (int width, int height)

Возвращает базовую линию.

47

Component.BaselineResizeBehavior getBaselineResizeBehavior ()

Возвращает перечисление, указывающее, как изменяется базовая линия компонента при изменении размера.

48

Прямоугольник getBounds ()

Получает границы этого компонента в форме объекта Rectangle.

49

Прямоугольник getBounds (Rectangle rv)

Сохраняет границы этого компонента в возвращаемое значение rv и возвращает rv.

50

ColorModel getColorModel ()

Получает экземпляр ColorModel, используемый для отображения компонента на устройстве вывода.

51

Компонент getComponentAt (int x, int y)

Определяет, содержит ли этот компонент или один из его непосредственных подкомпонентов расположение (x, y), и, если да, возвращает содержащий компонент.

52

Компонент getComponentAt (точка p)

Возвращает компонент или подкомпонент, который содержит указанную точку.

53

ComponentListener [] getComponentListeners ()

Возвращает массив всех слушателей компонента, зарегистрированных на этом компоненте.

54

ComponentOrientation getComponentOrientation ()

Получает чувствительную к языку ориентацию, которая должна использоваться для упорядочивания элементов или текста в этом компоненте.

55

Курсор getCursor ()

Получает курсор, установленный в компоненте.

56

DropTarget getDropTarget ()

Получает DropTarget, связанный с этим Компонентом.

57

Контейнер getFocusCycleRootAncestor ()

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

58

FocusListener [] getFocusListeners ()

Возвращает массив всех слушателей фокуса, зарегистрированных на этом компоненте.

59

Установите <AWTKeyStroke> getFocusTraversalKeys (int id)

Возвращает Набор ключей обхода фокуса для данной операции обхода для этого Компонента.

60

логическое значение getFocusTraversalKeysEnabled ()

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

61

Шрифт getFont ()

Получает шрифт этого компонента.

62

FontMetrics getFontMetrics (шрифт шрифта)

Получает метрики шрифта для указанного шрифта.

63

Цвет getForeground ()

Получает цвет переднего плана этого компонента.

64

Графика getGraphics ()

Создает графический контекст для этого компонента.

65

GraphicsConfiguration getGraphicsConfiguration ()

Получает графическую конфигурацию, связанную с этим компонентом.

66

int getHeight ()

Возвращает текущую высоту этого компонента.

67

HierarchyBoundsListener [] getHierarchyBoundsListeners ()

Возвращает массив всех слушателей границ иерархии, зарегистрированных в этом компоненте.

68

HierarchyListener [] getHierarchyListeners ()

Возвращает массив всех слушателей иерархии, зарегистрированных в этом компоненте.

69

логическое значение getIgnoreRepaint ()

70

InputContext getInputContext ()

Получает контекст ввода, используемый этим компонентом для обработки связи с методами ввода, когда текст вводится в этот компонент.

71

InputMethodListener [] getInputMethodListeners ()

Возвращает массив всех слушателей метода ввода, зарегистрированных в этом компоненте.

72

InputMethodRequests getInputMethodRequests ()

Получает обработчик запроса метода ввода, который поддерживает запросы от методов ввода для этого компонента.

73

KeyListener [] getKeyListeners ()

Возвращает массив всех ключевых слушателей, зарегистрированных в этом компоненте.

74

<T расширяет EventListener> T [] getListeners (Класс <T> listenerType)

Возвращает массив всех объектов, зарегистрированных в данный момент как FooListeners для этого компонента.

75

Locale getLocale ()

Получает языковой стандарт этого компонента.

76

Точка getLocation ()

Получает расположение этого компонента в форме точки, указывающей верхний левый угол компонента.

77

Point getLocation (Point rv)

Сохраняет источник x, y этого компонента в возвращаемое значение rv и возвращает rv.

78

Точка getLocationOnScreen ()

Получает расположение этого компонента в форме точки, указывающей верхний левый угол компонента в координатном пространстве экрана.

79

Размер getMaximumSize ()

Получает максимальный размер этого компонента.

80

Размер getMinimumSize ()

Получает минимальный размер этого компонента.

81

MouseListener [] getMouseListeners ()

Возвращает массив всех слушателей мыши, зарегистрированных в этом компоненте.

82

MouseMotionListener [] getMouseMotionListeners ()

Возвращает массив всех слушателей движения мыши, зарегистрированных в этом компоненте.

83

Point getMousePosition ()

Возвращает положение указателя мыши в координатном пространстве этого компонента, если компонент находится непосредственно под указателем мыши, в противном случае возвращает ноль.

84

MouseWheelListener [] getMouseWheelListeners ()

Возвращает массив всех слушателей колеса мыши, зарегистрированных на этом компоненте.

85

Строка getName ()

Получает имя компонента.

86

Контейнер getParent ()

Получает родителя этого компонента.

87

java.awt.peer.ComponentPeer getPeer () Устаревший. Начиная с версии 1.1 JDK, программы не должны напрямую манипулировать одноранговыми узлами; заменено на логическое isDisplayable ().

88

Размер getPreferredSize ()

Получает предпочтительный размер этого компонента.

89

PropertyChangeListener [] getPropertyChangeListeners ()

Возвращает массив всех слушателей изменения свойств, зарегистрированных в этом компоненте.

90

PropertyChangeListener [] getPropertyChangeListeners (String propertyName)

Возвращает массив всех слушателей, которые были связаны с именованным свойством.

91

Размер getSize ()

Возвращает размер этого компонента в форме объекта измерения.

92

Dimension getSize (Dimension rv) Сохраняет ширину / высоту этого компонента в возвращаемом значении rv и возвращает rv.

93

Инструментарий getToolkit ()

Получает инструментарий этого компонента.

94

Объект getTreeLock ()

Получает объект блокировки этого компонента (объект, которому принадлежит монитор синхронизации потоков)

для AWT дерева компонентов и операций макета.

95

int getWidth ()

Возвращает текущую ширину этого компонента.

96

int getX ()

Возвращает текущую координату x источника компонентов.

97

int getY ()

Возвращает текущую координату y начала координат компонентов.

98

boolean gotFocus (событие evt, объект чего)

Устаревшее. Начиная с версии 1.1 JDK, заменено на processFocusEvent (FocusEvent)

,

99

логическое handleEvent (событие evt)

Устаревшее. Начиная с версии 1.1 JDK заменен processEvent (AWTEvent).

100

логическое значение hasFocus ()

Возвращает true, если этот Компонент является владельцем фокуса.

101

void hide ()

Устаревшее. Начиная с версии 1.1 JDK, заменено на setVisible (логическое).

102

boolean imageUpdate (Image img, int infoflags, int x, int y, int w, int h)

Перекрашивает компонент, когда изображение изменилось.

103

логическое значение внутри (int x, int y)

Устаревшее. Начиная с версии 1.1 JDK, заменено на содержит (int, int).

104

void invalidate ()

Делает недействительным этот компонент.

105

логическое значение isBackgroundSet ()

Возвращает, был ли цвет фона явно установлен для этого компонента.

106

логический isCursorSet ()

Возвращает, был ли курсор явно установлен для этого компонента.

107

логическое isDisplayable ()

Определяет, отображается ли этот компонент.

108

логическое isDoubleBuffered ()

Возвращает true, если этот компонент закрашен в изображение за пределами экрана ( буфер )

это скопировано на экран позже.

109

логическое isEnabled ()

Определяет, включен ли этот компонент.

110

логическое isFocusable ()

Возвращает, может ли этот компонент быть сфокусирован.

111

логический isFocusCycleRoot (Контейнерный контейнер)

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

112

логическое isFocusOwner ()

Возвращает true, если этот Компонент является владельцем фокуса.

113

логическое isFocusTraversable ()

Устаревшее. Начиная с 1.4, заменено isFocusable ().

114

логическое isFontSet ()

Возвращает, был ли шрифт явно установлен для этого компонента.

115

логическое isForegroundSet ()

Возвращает, был ли цвет переднего плана явно установлен для этого компонента.

116

логический isLightweight ()

У легкого компонента нет нативного аналога инструментария.

117

логический isMaximumSizeSet ​​()

Возвращает true, если максимальный размер был установлен в ненулевое значение, в противном случае возвращает false.

118

логический isMinimumSizeSet ​​()

Возвращает, был ли setMinimumSize вызван с ненулевым значением.

119

логический isOpaque ()

Возвращает true, если этот компонент полностью непрозрачный, по умолчанию возвращает false.

120

логическое isPreferredSizeSet ​​()

Возвращает true, если предпочтительный размер был установлен в ненулевое значение, в противном случае возвращает false.

121

логическое isShowing ()

Определяет, отображается ли этот компонент на экране.

122

логическое значение isValid ()

Определяет, является ли этот компонент действительным.

123

логическое значение isVisible ()

Определяет, должен ли этот компонент быть видимым, когда его родительский элемент видим.

124

логическое keyDown (событие evt, int key)

Устаревшее. Начиная с версии 1.1 JDK, заменено на processKeyEvent (KeyEvent).

125

логическое keyUp (событие evt, int key)

Устаревшее. Начиная с версии 1.1 JDK, заменено на processKeyEvent (KeyEvent).

126

пустое расположение ()

Устаревшее. Начиная с версии 1.1 JDK, заменено на doLayout ().

127

список недействительных ()

Распечатывает список этого компонента в стандартный поток вывода системы System.out.

128

список пустот (PrintStream out)

Распечатывает список этого компонента в указанном потоке вывода.

129

список пустот (PrintStream out, int indent)

Распечатывает список, начиная с указанного отступа, в указанный поток печати.

130

список пустот (PrintWriter out)

Распечатывает список для указанного автора печати.

131

список пустот (PrintWriter out, int indent)

Распечатывает список, начиная с указанного отступа, для указанного средства печати.

132

Расположение компонента (int x, int y)

Устаревшее. Начиная с версии 1.1 JDK, заменено на getComponentAt (int, int).

133

Точка расположения ()

Устаревшее. Начиная с версии 1.1 JDK, заменено getLocation ().

134

логическое lostFocus (событие evt, объект чего)

Устаревшее. Начиная с версии 1.1 JDK, заменено на processFocusEvent (FocusEvent).

135

логическое значение mouseDown (событие evt, int x, int y)

Устаревшее. Начиная с версии 1.1 JDK, заменено на processMouseEvent (MouseEvent).

136

логический mouseDrag (событие evt, int x, int y)

Устаревшее. Начиная с версии 1.1 JDK, заменено на processMouseMotionEvent (MouseEvent).

137

логический mouseEnter (событие evt, int x, int y)

Устаревшее. Начиная с версии 1.1 JDK, заменено на processMouseEvent (MouseEvent).

138

boolean mouseExit (Событие evt, int x, int y)

Устаревшее. Начиная с версии 1.1 JDK, заменено на processMouseEvent (MouseEvent).

139

логическое mouseMove (событие evt, int x, int y)

Устаревшее. Начиная с версии 1.1 JDK, заменено на processMouseMotionEvent (MouseEvent).

140

логическое mouseUp (событие evt, int x, int y)

Устаревшее. Начиная с версии 1.1 JDK, заменено на processMouseEvent (MouseEvent).

141

движение void (int x, int y)

Устаревшее. Начиная с версии 1.1 JDK, заменено на setLocation (int, int).

142

void nextFocus ()

Устаревшее. Начиная с версии 1.1 JDK, заменено на TransferFocus ().

143

пустота краски (графика г)

Красит этот компонент.

144

void paintAll (Графика г)

Рисует этот компонент и все его подкомпоненты.

145

логическое postEvent (событие e)

Устаревшее. Начиная с версии 1.1 JDK, заменено на dispatchEvent (AWTEvent).

146

логическое prepareImage (изображение изображения, ширина int, высота int, наблюдатель ImageObserver)

Подготавливает изображение для рендеринга на этом компоненте с указанной шириной и высотой.

147

Пустая печать (Графика г)

Печатает этот компонент.

148

void printAll (Графика г)

Печатает этот компонент и все его подкомпоненты.

149

protectedvoid processComponentEvent (ComponentEvent e)

Обрабатывает события компонента, происходящие в этом компоненте, путем отправки их всем зарегистрированным объектам ComponentListener.

150

Защищенный процесс vEventEvent (AWTEvent e)

Обрабатывает события, происходящие на этом компоненте.

151

защищенный void processFocusEvent (FocusEvent e)

Обрабатывает события фокуса, происходящие на этом компоненте, отправляя их всем зарегистрированным объектам FocusListener.

152

защищенный void processHierarchyBoundsEvent (HierarchyEvent e)

Обрабатывает события границ иерархии, происходящие в этом компоненте, путем отправки их всем зарегистрированным объектам HierarchyBoundsListener.

153

Защищенный void processHierarchyEvent (HierarchyEvent e)

Обрабатывает события иерархии, происходящие в этом компоненте, путем отправки их всем зарегистрированным объектам HierarchyListener.

154

protectedvoid processInputMethodEvent (InputMethodEvent e)

Обрабатывает события метода ввода, происходящие в этом компоненте, путем отправки их всем зарегистрированным объектам InputMethodListener.

155

защищенный void processKeyEvent (KeyEvent e)

Обрабатывает ключевые события, происходящие в этом компоненте, путем отправки их всем зарегистрированным объектам KeyListener.

156

защищенный void processMouseEvent (MouseEvent e)

Обрабатывает события мыши, происходящие в этом компоненте, путем отправки их всем зарегистрированным объектам MouseListener.

157

защищенный процесс voidMouseMotionEvent (MouseEvent e)

Обрабатывает события движения мыши, возникающие в этом компоненте, путем отправки их всем зарегистрированным объектам MouseMotionListener.

158

Защищенный void processMouseWheelEvent (MouseWheelEvent e)

Обрабатывает события колеса мыши, возникающие в этом компоненте, путем отправки их всем зарегистрированным объектам MouseWheelListener.

159

void удалить (всплывающее окно MenuComponent)

Удаляет указанное всплывающее меню из компонента.

160

void removeComponentListener (ComponentListener l)

Удаляет указанный прослушиватель компонента, чтобы он больше не получал события компонента от этого компонента.

161

void removeFocusListener (FocusListener l)

Удаляет указанный слушатель фокуса, чтобы он больше не получал события фокуса от этого компонента.

162

void removeHierarchyBoundsListener (HierarchyBoundsListener l)

Удаляет указанный прослушиватель границ иерархии, чтобы он больше не получал события границ иерархии от этого компонента.

163

void removeHierarchyListener (HierarchyListener l)

Удаляет указанный прослушиватель иерархии, чтобы он больше не получал события изменения иерархии от этого компонента.

164

void removeInputMethodListener (InputMethodListener l)

Удаляет указанный прослушиватель метода ввода, чтобы он больше не получал события метода ввода от этого компонента.

165

void removeKeyListener (KeyListener l)

Удаляет указанный прослушиватель ключей, чтобы он больше не получал события клавиш от этого компонента.

166

void removeMouseListener (MouseListener l)

Удаляет указанный прослушиватель мыши, чтобы он больше не получал события мыши от этого компонента.

167

void removeMouseMotionListener (MouseMotionListener l)

Удаляет указанный слушатель движения мыши, чтобы он больше не получал события движения мыши от этого компонента.

168

void removeMouseWheelListener (MouseWheelListener l)

Удаляет указанный прослушиватель колеса мыши, чтобы он больше не получал события колеса мыши от этого компонента.

169

void removeNotify ()

Делает этот компонент недоступным для просмотра, уничтожая его собственный ресурс экрана.

170

void removePropertyChangeListener (слушатель PropertyChangeListener)

Удаляет PropertyChangeListener из списка слушателей.

171

void removePropertyChangeListener (String propertyName, прослушиватель PropertyChangeListener)

Удаляет PropertyChangeListener из списка слушателей для определенного свойства.

172

void repaint ()

Перекрашивает этот компонент.

173

void repaint (int x, int y, int width, int height)

Перерисовывает указанный прямоугольник этого компонента.

174

Пустота перекрасить (долго тм)

Перекрашивает компонент.

175

void repaint (long tm, int x, int y, int width, int height)

Перекрашивает указанный прямоугольник этого компонента в течение миллисекунд.

176

void requestFocus ()

Требует, чтобы этот Компонент получил фокус ввода, и чтобы предок верхнего уровня этого Компонента стал сфокусированным Окном.

177

защищенный логический requestFocus (логический временный)

Требует, чтобы этот Компонент получил фокус ввода, и чтобы предок верхнего уровня этого Компонента стал сфокусированным Окном.

178

логический requestFocusInWindow ()

Запрашивает, чтобы этот Компонент получил фокус ввода, если предок верхнего уровня этого Компонента уже является сфокусированным Окном.

179

защищенный логический requestFocusInWindow (логический временный)

Запрашивает, чтобы этот Компонент получил фокус ввода, если предок верхнего уровня этого Компонента уже является сфокусированным Окном.

180

изменение формы void (int x, int y, int width, int height)

Устаревшее. Начиная с версии 1.1 JDK, заменено на setBounds (int, int, int, int).

181

изменение размера пустоты (размер d)

Устаревшее. Начиная с версии 1.1 JDK, заменено на setSize (Dimension).

182

изменение размера пустоты (int width, int height)

Устаревшее. Начиная с версии 1.1 JDK, заменено на setSize (int, int).

183

void setBackground (Color c)

Устанавливает цвет фона этого компонента.

184

void setBounds (int x, int y, int width, int height)

Перемещает и изменяет размеры этого компонента.

185

void setBounds (Rectangle r)

Перемещает и изменяет размеры этого компонента, чтобы соответствовать новому ограничивающему прямоугольнику r.

186

void setComponentOrientation (ComponentOrientation o)

Устанавливает чувствительную к языку ориентацию, которая должна использоваться для упорядочения элементов или текста в этом компоненте.

187

void setCursor (курсор курсора)

Устанавливает изображение курсора на указанный курсор.

188

void setDropTarget (DropTarget dt)

Свяжите DropTarget с этим компонентом.

189

void setEnabled (логическое значение b)

Включает или отключает этот компонент, в зависимости от значения параметра b.

190

void setFocusable (логическая фокусировка)

Устанавливает фокусируемое состояние этого компонента на указанное значение.

191

void setFocusTraversalKeys (int id, Set <? extends AWTKeyStroke> нажатия клавиш)

Устанавливает ключи обхода фокуса для данной операции обхода для этого Компонента.

192

void setFocusTraversalKeysEnabled (логическое focusTraversalKeysEnabled)

Устанавливает, включены ли клавиши обхода фокуса для этого компонента.

193

void setFont (Font f)

Устанавливает шрифт этого компонента.

194

void setForeground (Color c)

Устанавливает цвет переднего плана этого компонента.

195

void setIgnoreRepaint (логическое игнорированиеRepaint)

Устанавливает, следует ли игнорировать сообщения рисования, полученные из операционной системы.

196

void setLocale (Locale l)

Устанавливает локаль этого компонента.

197

void setLocation (int x, int y)

Перемещает этот компонент в новое место.

198

void setLocation (точка p)

Перемещает этот компонент в новое место.

199

void setMaximumSize (размер максимальный размер)

Устанавливает максимальный размер этого компонента на постоянное значение.

200

void setMinimumSize (DimensionimumSize)

Устанавливает минимальный размер этого компонента в постоянное значение.

201

void setName (String name)

Устанавливает имя компонента в указанную строку.

202

void setPreferredSize (размер предпочтительного размера)

Устанавливает предпочтительный размер этого компонента в постоянное значение.

203

void setSize (Размер d)

Изменяет размеры этого компонента, чтобы он имел ширину d.width и высоту d.height.

204

void setSize (int width, int height)

Изменяет размеры этого компонента так, чтобы он имел ширину, ширину и высоту.

205

void setVisible (логическое значение b)

Показывает или скрывает этот компонент в зависимости от значения параметра b.

206

void show ()

Устаревшее. Начиная с версии 1.1 JDK, заменено на setVisible (логическое).

207

пустое шоу (булево b)

Устаревшее. Начиная с версии 1.1 JDK, заменено на setVisible (логическое).

208

Размер размер ()

Устаревшее. Начиная с версии 1.1 JDK, заменено getSize ().

209

Строка toString ()

Возвращает строковое представление этого компонента и его значения.

210

void TransferFocus ()

Переносит фокус на следующий компонент, как если бы этот компонент был владельцем фокуса.

211

void TransferFocusBackward ()

Переносит фокус на предыдущий компонент, как если бы этот компонент был владельцем фокуса.

212

void TransferFocusUpCycle ()

Переносит фокус вверх на один цикл обхода фокуса.

213

Пустое обновление (Графика г)

Обновляет этот компонент.

214

void validate ()

Гарантирует, что этот компонент имеет допустимый макет.

215

Границы прямоугольника ()

Устаревшее. Начиная с версии 1.1 JDK, заменено getBounds ().

216

защищенное событие AWTEvent coalesceEvents (существующее событие AWTEvent, новое событие AWTEvent)

Потенциально объединить событие, публикуемое с существующим событием.

217

Защищенная строка paramString ()

Возвращает строку, представляющую состояние этого компонента.

218

Защищенный void firePropertyChange (String propertyName, int oldValue, int newValue)

Поддержка отчетов об изменениях связанных свойств для целочисленных свойств.

219

Размер предпочитаемый размер ()

Устаревшее. Начиная с версии 1.1 JDK, заменено на getPreferredSize ().

220

логическое prepareImage (изображение, обозреватель ImageObserver)

Подготавливает изображение для рендеринга на этом компоненте.

221

Размер MinimumSize ()

Устаревшее. Начиная с версии 1.1 JDK, заменено getMinimumSize ().

логическое действие (событие evt, объект чего)

Устаревшее. Начиная с версии 1.1 JDK, этот компонент должен регистрироваться как ActionListener для компонента, который запускает события действия.

void add (PopupMenu popup)

Добавляет указанное всплывающее меню к компоненту.

void addComponentListener (ComponentListener l)

Добавляет указанный слушатель компонента для получения событий компонента от этого компонента.

void addFocusListener (FocusListener l)

Добавляет указанный слушатель фокуса для получения событий фокуса от этого компонента, когда этот компонент получает фокус ввода.

void addHierarchyBoundsListener (HierarchyBoundsListener l)

Добавляет указанный прослушиватель границ иерархии для получения событий границ иерархии от этого компонента, когда изменяется иерархия, к которой принадлежит этот контейнер.

void addHierarchyListener (HierarchyListener l)

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

void addInputMethodListener (InputMethodListener l)

Добавляет указанный прослушиватель метода ввода для получения событий метода ввода от этого компонента.

void addKeyListener (KeyListener l)

Добавляет указанный ключевой слушатель, чтобы получить ключевые события от этого компонента.

void addMouseListener (MouseListener l)

Добавляет указанный слушатель мыши для получения событий мыши от этого компонента.

void addMouseMotionListener (MouseMotionListener l)

Добавляет указанный слушатель движения мыши, чтобы получать события движения мыши от этого компонента.

void addMouseWheelListener (MouseWheelListener l)

Добавляет указанный слушатель колеса мыши для получения событий колеса мыши от этого компонента.

void addNotify ()

Делает этот компонент отображаемым, подключая его к собственному экранному ресурсу.

void addPropertyChangeListener (слушатель PropertyChangeListener)

Добавляет PropertyChangeListener в список слушателей.

void addPropertyChangeListener (String propertyName, прослушиватель PropertyChangeListener)

Добавляет PropertyChangeListener в список слушателей для определенного свойства.

void applyComponentOrientation (ориентация компонента)

Устанавливает свойство ComponentOrientation этого компонента и всех компонентов, содержащихся в нем.

логическое значение areFocusTraversalKeysSet (int id)

Возвращает, был ли явно задан Набор ключей обхода фокуса для данной операции обхода фокуса для этого Компонента.

int checkImage (изображение, обозреватель ImageObserver)

Возвращает статус построения экранного представления указанного изображения.

int checkImage (изображение изображения, ширина int, высота int, наблюдатель ImageObserver)

Возвращает статус построения экранного представления указанного изображения.

логическое значение содержит (int x, int y)

Проверяет, «содержит» ли этот компонент указанную точку, где x и y определены как относящиеся к системе координат этого компонента.

логическое содержит (точка р)

Проверяет, «содержит» ли этот компонент указанную точку, где координаты точки x и y определены как относящиеся к системе координат этого компонента.

Image createImage (производитель ImageProducer)

Создает изображение из указанного производителя изображений.

Изображение createImage (int width, int height)

Создает закадровое нарисованное изображение, которое будет использоваться для двойной буферизации.

VolatileImage createVolatileImage (int width, int height)

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

VolatileImage createVolatileImage (int ширина, int высота, ограничения ImageCapabilities)

Создает нестабильное закадровое нарисованное изображение с заданными возможностями.

void deliveryEvent (Событие e)

Устаревшее. Начиная с версии 1.1 JDK, заменено на dispatchEvent (AWTEvent e).

void disable ()

Устаревшее. Начиная с версии 1.1 JDK, заменено на setEnabled (логическое).

Защищенный void disableEvents (long eventsToDisable)

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

void dispatchEvent (AWTEvent e)

Отправляет событие этому компоненту или одному из его подкомпонентов.

void doLayout ()

Предлагает диспетчеру компоновки выложить этот компонент.

void enable ()

Устаревшее. Начиная с версии 1.1 JDK, заменено на setEnabled (логическое).

void enable (логическое значение b)

Устаревшее. Начиная с версии 1.1 JDK, заменено на setEnabled (логическое).

Защищенный void enableEvents (long eventsToEnable)

Включает события, определенные указанным параметром маски события, для доставки этому компоненту.

void enableInputMethods (логическое включение)

Включает или отключает поддержку метода ввода для этого компонента.

защищенный void firePropertyChange (строковое propertyName, логическое oldValue, логическое newValue)

Поддержка отчетов об изменениях связанных свойств для логических свойств.

void firePropertyChange (String propertyName, байт oldValue, байт newValue)

Сообщает о связанном изменении свойства.

void firePropertyChange (String propertyName, char oldValue, char newValue)

Сообщает о связанном изменении свойства.

void firePropertyChange (String propertyName, double oldValue, double newValue)

Сообщает о связанном изменении свойства.

void firePropertyChange (String propertyName, float oldValue, float newValue)

Сообщает о связанном изменении свойства.

void firePropertyChange (String propertyName, long oldValue, long newValue)

Сообщает о связанном изменении свойства.

Защищенный void firePropertyChange (String propertyName, Объект oldValue, Объект newValue)

Поддержка отчетов об изменениях связанных свойств для свойств объекта.

void firePropertyChange (String propertyName, короткое oldValue, короткое newValue)

Сообщает о связанном изменении свойства.

AccessibleContext getAccessibleContext ()

Получает AccessibleContext, связанный с этим Компонентом.

float getAlignmentX ()

Возвращает выравнивание по оси x.

float getAlignmentY ()

Возвращает выравнивание по оси Y.

Цвет getBackground ()

Получает цвет фона этого компонента.

int getBaseline (int width, int height)

Возвращает базовую линию.

Component.BaselineResizeBehavior getBaselineResizeBehavior ()

Возвращает перечисление, указывающее, как изменяется базовая линия компонента при изменении размера.

Прямоугольник getBounds ()

Получает границы этого компонента в форме объекта Rectangle.

Прямоугольник getBounds (Rectangle rv)

Сохраняет границы этого компонента в возвращаемое значение rv и возвращает rv.

ColorModel getColorModel ()

Получает экземпляр ColorModel, используемый для отображения компонента на устройстве вывода.

Компонент getComponentAt (int x, int y)

Определяет, содержит ли этот компонент или один из его непосредственных подкомпонентов расположение (x, y), и, если да, возвращает содержащий компонент.

Компонент getComponentAt (точка p)

Возвращает компонент или подкомпонент, который содержит указанную точку.

ComponentListener [] getComponentListeners ()

Возвращает массив всех слушателей компонента, зарегистрированных на этом компоненте.

ComponentOrientation getComponentOrientation ()

Получает чувствительную к языку ориентацию, которая должна использоваться для упорядочивания элементов или текста в этом компоненте.

Курсор getCursor ()

Получает курсор, установленный в компоненте.

DropTarget getDropTarget ()

Получает DropTarget, связанный с этим Компонентом.

Контейнер getFocusCycleRootAncestor ()

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

FocusListener [] getFocusListeners ()

Возвращает массив всех слушателей фокуса, зарегистрированных на этом компоненте.

Установите <AWTKeyStroke> getFocusTraversalKeys (int id)

Возвращает Набор ключей обхода фокуса для данной операции обхода для этого Компонента.

логическое значение getFocusTraversalKeysEnabled ()

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

Шрифт getFont ()

Получает шрифт этого компонента.

FontMetrics getFontMetrics (шрифт шрифта)

Получает метрики шрифта для указанного шрифта.

Цвет getForeground ()

Получает цвет переднего плана этого компонента.

Графика getGraphics ()

Создает графический контекст для этого компонента.

GraphicsConfiguration getGraphicsConfiguration ()

Получает графическую конфигурацию, связанную с этим компонентом.

int getHeight ()

Возвращает текущую высоту этого компонента.

HierarchyBoundsListener [] getHierarchyBoundsListeners ()

Возвращает массив всех слушателей границ иерархии, зарегистрированных в этом компоненте.

HierarchyListener [] getHierarchyListeners ()

Возвращает массив всех слушателей иерархии, зарегистрированных в этом компоненте.

логическое значение getIgnoreRepaint ()

InputContext getInputContext ()

Получает контекст ввода, используемый этим компонентом для обработки связи с методами ввода, когда текст вводится в этот компонент.

InputMethodListener [] getInputMethodListeners ()

Возвращает массив всех слушателей метода ввода, зарегистрированных в этом компоненте.

InputMethodRequests getInputMethodRequests ()

Получает обработчик запроса метода ввода, который поддерживает запросы от методов ввода для этого компонента.

KeyListener [] getKeyListeners ()

Возвращает массив всех ключевых слушателей, зарегистрированных в этом компоненте.

<T расширяет EventListener> T [] getListeners (Класс <T> listenerType)

Возвращает массив всех объектов, зарегистрированных в данный момент как FooListeners для этого компонента.

Locale getLocale ()

Получает языковой стандарт этого компонента.

Точка getLocation ()

Получает расположение этого компонента в форме точки, указывающей верхний левый угол компонента.

Point getLocation (Point rv)

Сохраняет источник x, y этого компонента в возвращаемое значение rv и возвращает rv.

Точка getLocationOnScreen ()

Получает расположение этого компонента в форме точки, указывающей верхний левый угол компонента в координатном пространстве экрана.

Размер getMaximumSize ()

Получает максимальный размер этого компонента.

Размер getMinimumSize ()

Получает минимальный размер этого компонента.

MouseListener [] getMouseListeners ()

Возвращает массив всех слушателей мыши, зарегистрированных в этом компоненте.

MouseMotionListener [] getMouseMotionListeners ()

Возвращает массив всех слушателей движения мыши, зарегистрированных в этом компоненте.

Point getMousePosition ()

Возвращает положение указателя мыши в координатном пространстве этого компонента, если компонент находится непосредственно под указателем мыши, в противном случае возвращает ноль.

MouseWheelListener [] getMouseWheelListeners ()

Возвращает массив всех слушателей колеса мыши, зарегистрированных на этом компоненте.

Строка getName ()

Получает имя компонента.

Контейнер getParent ()

Получает родителя этого компонента.

java.awt.peer.ComponentPeer getPeer () Устаревший. Начиная с версии 1.1 JDK, программы не должны напрямую манипулировать одноранговыми узлами; заменено на логическое isDisplayable ().

Размер getPreferredSize ()

Получает предпочтительный размер этого компонента.

PropertyChangeListener [] getPropertyChangeListeners ()

Возвращает массив всех слушателей изменения свойств, зарегистрированных в этом компоненте.

PropertyChangeListener [] getPropertyChangeListeners (String propertyName)

Возвращает массив всех слушателей, которые были связаны с именованным свойством.

Размер getSize ()

Возвращает размер этого компонента в форме объекта измерения.

Dimension getSize (Dimension rv) Сохраняет ширину / высоту этого компонента в возвращаемом значении rv и возвращает rv.

Инструментарий getToolkit ()

Получает инструментарий этого компонента.

Объект getTreeLock ()

Получает объект блокировки этого компонента (объект, которому принадлежит монитор синхронизации потоков)

для AWT дерева компонентов и операций макета.

int getWidth ()

Возвращает текущую ширину этого компонента.

int getX ()

Возвращает текущую координату x источника компонентов.

int getY ()

Возвращает текущую координату y начала координат компонентов.

boolean gotFocus (событие evt, объект чего)

Устаревшее. Начиная с версии 1.1 JDK, заменено на processFocusEvent (FocusEvent)

,

логическое handleEvent (событие evt)

Устаревшее. Начиная с версии 1.1 JDK заменен processEvent (AWTEvent).

логическое значение hasFocus ()

Возвращает true, если этот Компонент является владельцем фокуса.

void hide ()

Устаревшее. Начиная с версии 1.1 JDK, заменено на setVisible (логическое).

boolean imageUpdate (Image img, int infoflags, int x, int y, int w, int h)

Перекрашивает компонент, когда изображение изменилось.

логическое значение внутри (int x, int y)

Устаревшее. Начиная с версии 1.1 JDK, заменено на содержит (int, int).

void invalidate ()

Делает недействительным этот компонент.

логическое значение isBackgroundSet ()

Возвращает, был ли цвет фона явно установлен для этого компонента.

логический isCursorSet ()

Возвращает, был ли курсор явно установлен для этого компонента.

логическое isDisplayable ()

Определяет, отображается ли этот компонент.

логическое isDoubleBuffered ()

Возвращает true, если этот компонент закрашен в изображение за пределами экрана ( буфер )

это скопировано на экран позже.

логическое isEnabled ()

Определяет, включен ли этот компонент.

логическое isFocusable ()

Возвращает, может ли этот компонент быть сфокусирован.

логический isFocusCycleRoot (Контейнерный контейнер)

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

логическое isFocusOwner ()

Возвращает true, если этот Компонент является владельцем фокуса.

логическое isFocusTraversable ()

Устаревшее. Начиная с 1.4, заменено isFocusable ().

логическое isFontSet ()

Возвращает, был ли шрифт явно установлен для этого компонента.

логическое isForegroundSet ()

Возвращает, был ли цвет переднего плана явно установлен для этого компонента.

логический isLightweight ()

У легкого компонента нет нативного аналога инструментария.

логический isMaximumSizeSet ​​()

Возвращает true, если максимальный размер был установлен в ненулевое значение, в противном случае возвращает false.

логический isMinimumSizeSet ​​()

Возвращает, был ли setMinimumSize вызван с ненулевым значением.

логический isOpaque ()

Возвращает true, если этот компонент полностью непрозрачный, по умолчанию возвращает false.

логическое isPreferredSizeSet ​​()

Возвращает true, если предпочтительный размер был установлен в ненулевое значение, в противном случае возвращает false.

логическое isShowing ()

Определяет, отображается ли этот компонент на экране.

логическое значение isValid ()

Определяет, является ли этот компонент действительным.

логическое значение isVisible ()

Определяет, должен ли этот компонент быть видимым, когда его родительский элемент видим.

логическое keyDown (событие evt, int key)

Устаревшее. Начиная с версии 1.1 JDK, заменено на processKeyEvent (KeyEvent).

логическое keyUp (событие evt, int key)

Устаревшее. Начиная с версии 1.1 JDK, заменено на processKeyEvent (KeyEvent).

пустое расположение ()

Устаревшее. Начиная с версии 1.1 JDK, заменено на doLayout ().

список недействительных ()

Распечатывает список этого компонента в стандартный поток вывода системы System.out.

список пустот (PrintStream out)

Распечатывает список этого компонента в указанном потоке вывода.

список пустот (PrintStream out, int indent)

Распечатывает список, начиная с указанного отступа, в указанный поток печати.

список пустот (PrintWriter out)

Распечатывает список для указанного автора печати.

список пустот (PrintWriter out, int indent)

Распечатывает список, начиная с указанного отступа, для указанного средства печати.

Расположение компонента (int x, int y)

Устаревшее. Начиная с версии 1.1 JDK, заменено на getComponentAt (int, int).

Точка расположения ()

Устаревшее. Начиная с версии 1.1 JDK, заменено getLocation ().

логическое lostFocus (событие evt, объект чего)

Устаревшее. Начиная с версии 1.1 JDK, заменено на processFocusEvent (FocusEvent).

логическое значение mouseDown (событие evt, int x, int y)

Устаревшее. Начиная с версии 1.1 JDK, заменено на processMouseEvent (MouseEvent).

логический mouseDrag (событие evt, int x, int y)

Устаревшее. Начиная с версии 1.1 JDK, заменено на processMouseMotionEvent (MouseEvent).

логический mouseEnter (событие evt, int x, int y)

Устаревшее. Начиная с версии 1.1 JDK, заменено на processMouseEvent (MouseEvent).

boolean mouseExit (Событие evt, int x, int y)

Устаревшее. Начиная с версии 1.1 JDK, заменено на processMouseEvent (MouseEvent).

логическое mouseMove (событие evt, int x, int y)

Устаревшее. Начиная с версии 1.1 JDK, заменено на processMouseMotionEvent (MouseEvent).

логическое mouseUp (событие evt, int x, int y)

Устаревшее. Начиная с версии 1.1 JDK, заменено на processMouseEvent (MouseEvent).

движение void (int x, int y)

Устаревшее. Начиная с версии 1.1 JDK, заменено на setLocation (int, int).

void nextFocus ()

Устаревшее. Начиная с версии 1.1 JDK, заменено на TransferFocus ().

пустота краски (графика г)

Красит этот компонент.

void paintAll (Графика г)

Рисует этот компонент и все его подкомпоненты.

логическое postEvent (событие e)

Устаревшее. Начиная с версии 1.1 JDK, заменено на dispatchEvent (AWTEvent).

логическое prepareImage (изображение изображения, ширина int, высота int, наблюдатель ImageObserver)

Подготавливает изображение для рендеринга на этом компоненте с указанной шириной и высотой.

Пустая печать (Графика г)

Печатает этот компонент.

void printAll (Графика г)

Печатает этот компонент и все его подкомпоненты.

protectedvoid processComponentEvent (ComponentEvent e)

Обрабатывает события компонента, происходящие в этом компоненте, путем отправки их всем зарегистрированным объектам ComponentListener.

Защищенный процесс vEventEvent (AWTEvent e)

Обрабатывает события, происходящие на этом компоненте.

защищенный void processFocusEvent (FocusEvent e)

Обрабатывает события фокуса, происходящие на этом компоненте, отправляя их всем зарегистрированным объектам FocusListener.

защищенный void processHierarchyBoundsEvent (HierarchyEvent e)

Обрабатывает события границ иерархии, происходящие в этом компоненте, путем отправки их всем зарегистрированным объектам HierarchyBoundsListener.

Защищенный void processHierarchyEvent (HierarchyEvent e)

Обрабатывает события иерархии, происходящие в этом компоненте, путем отправки их всем зарегистрированным объектам HierarchyListener.

protectedvoid processInputMethodEvent (InputMethodEvent e)

Обрабатывает события метода ввода, происходящие в этом компоненте, путем отправки их всем зарегистрированным объектам InputMethodListener.

защищенный void processKeyEvent (KeyEvent e)

Обрабатывает ключевые события, происходящие в этом компоненте, путем отправки их всем зарегистрированным объектам KeyListener.

защищенный void processMouseEvent (MouseEvent e)

Обрабатывает события мыши, происходящие в этом компоненте, путем отправки их всем зарегистрированным объектам MouseListener.

защищенный процесс voidMouseMotionEvent (MouseEvent e)

Обрабатывает события движения мыши, возникающие в этом компоненте, путем отправки их всем зарегистрированным объектам MouseMotionListener.

Защищенный void processMouseWheelEvent (MouseWheelEvent e)

Обрабатывает события колеса мыши, возникающие в этом компоненте, путем отправки их всем зарегистрированным объектам MouseWheelListener.

void удалить (всплывающее окно MenuComponent)

Удаляет указанное всплывающее меню из компонента.

void removeComponentListener (ComponentListener l)

Удаляет указанный прослушиватель компонента, чтобы он больше не получал события компонента от этого компонента.

void removeFocusListener (FocusListener l)

Удаляет указанный слушатель фокуса, чтобы он больше не получал события фокуса от этого компонента.

void removeHierarchyBoundsListener (HierarchyBoundsListener l)

Удаляет указанный прослушиватель границ иерархии, чтобы он больше не получал события границ иерархии от этого компонента.

void removeHierarchyListener (HierarchyListener l)

Удаляет указанный прослушиватель иерархии, чтобы он больше не получал события изменения иерархии от этого компонента.

void removeInputMethodListener (InputMethodListener l)

Удаляет указанный прослушиватель метода ввода, чтобы он больше не получал события метода ввода от этого компонента.

void removeKeyListener (KeyListener l)

Удаляет указанный прослушиватель ключей, чтобы он больше не получал события клавиш от этого компонента.

void removeMouseListener (MouseListener l)

Удаляет указанный прослушиватель мыши, чтобы он больше не получал события мыши от этого компонента.

void removeMouseMotionListener (MouseMotionListener l)

Удаляет указанный слушатель движения мыши, чтобы он больше не получал события движения мыши от этого компонента.

void removeMouseWheelListener (MouseWheelListener l)

Удаляет указанный прослушиватель колеса мыши, чтобы он больше не получал события колеса мыши от этого компонента.

void removeNotify ()

Делает этот компонент недоступным для просмотра, уничтожая его собственный ресурс экрана.

void removePropertyChangeListener (слушатель PropertyChangeListener)

Удаляет PropertyChangeListener из списка слушателей.

void removePropertyChangeListener (String propertyName, прослушиватель PropertyChangeListener)

Удаляет PropertyChangeListener из списка слушателей для определенного свойства.

void repaint ()

Перекрашивает этот компонент.

void repaint (int x, int y, int width, int height)

Перерисовывает указанный прямоугольник этого компонента.

Пустота перекрасить (долго тм)

Перекрашивает компонент.

void repaint (long tm, int x, int y, int width, int height)

Перекрашивает указанный прямоугольник этого компонента в течение миллисекунд.

void requestFocus ()

Требует, чтобы этот Компонент получил фокус ввода, и чтобы предок верхнего уровня этого Компонента стал сфокусированным Окном.

защищенный логический requestFocus (логический временный)

Требует, чтобы этот Компонент получил фокус ввода, и чтобы предок верхнего уровня этого Компонента стал сфокусированным Окном.

логический requestFocusInWindow ()

Запрашивает, чтобы этот Компонент получил фокус ввода, если предок верхнего уровня этого Компонента уже является сфокусированным Окном.

защищенный логический requestFocusInWindow (логический временный)

Запрашивает, чтобы этот Компонент получил фокус ввода, если предок верхнего уровня этого Компонента уже является сфокусированным Окном.

изменение формы void (int x, int y, int width, int height)

Устаревшее. Начиная с версии 1.1 JDK, заменено на setBounds (int, int, int, int).

изменение размера пустоты (размер d)

Устаревшее. Начиная с версии 1.1 JDK, заменено на setSize (Dimension).

изменение размера пустоты (int width, int height)

Устаревшее. Начиная с версии 1.1 JDK, заменено на setSize (int, int).

void setBackground (Color c)

Устанавливает цвет фона этого компонента.

void setBounds (int x, int y, int width, int height)

Перемещает и изменяет размеры этого компонента.

void setBounds (Rectangle r)

Перемещает и изменяет размеры этого компонента, чтобы соответствовать новому ограничивающему прямоугольнику r.

void setComponentOrientation (ComponentOrientation o)

Устанавливает чувствительную к языку ориентацию, которая должна использоваться для упорядочения элементов или текста в этом компоненте.

void setCursor (курсор курсора)

Устанавливает изображение курсора на указанный курсор.

void setDropTarget (DropTarget dt)

Свяжите DropTarget с этим компонентом.

void setEnabled (логическое значение b)

Включает или отключает этот компонент, в зависимости от значения параметра b.

void setFocusable (логическая фокусировка)

Устанавливает фокусируемое состояние этого компонента на указанное значение.

void setFocusTraversalKeys (int id, Set <? extends AWTKeyStroke> нажатия клавиш)

Устанавливает ключи обхода фокуса для данной операции обхода для этого Компонента.

void setFocusTraversalKeysEnabled (логическое focusTraversalKeysEnabled)

Устанавливает, включены ли клавиши обхода фокуса для этого компонента.

void setFont (Font f)

Устанавливает шрифт этого компонента.

void setForeground (Color c)

Устанавливает цвет переднего плана этого компонента.

void setIgnoreRepaint (логическое игнорированиеRepaint)

Устанавливает, следует ли игнорировать сообщения рисования, полученные из операционной системы.

void setLocale (Locale l)

Устанавливает локаль этого компонента.

void setLocation (int x, int y)

Перемещает этот компонент в новое место.

void setLocation (точка p)

Перемещает этот компонент в новое место.

void setMaximumSize (размер максимальный размер)

Устанавливает максимальный размер этого компонента на постоянное значение.

void setMinimumSize (DimensionimumSize)

Устанавливает минимальный размер этого компонента в постоянное значение.

void setName (String name)

Устанавливает имя компонента в указанную строку.

void setPreferredSize (размер предпочтительного размера)

Устанавливает предпочтительный размер этого компонента в постоянное значение.

void setSize (Размер d)

Изменяет размеры этого компонента, чтобы он имел ширину d.width и высоту d.height.

void setSize (int width, int height)

Изменяет размеры этого компонента так, чтобы он имел ширину, ширину и высоту.

void setVisible (логическое значение b)

Показывает или скрывает этот компонент в зависимости от значения параметра b.

void show ()

Устаревшее. Начиная с версии 1.1 JDK, заменено на setVisible (логическое).

пустое шоу (булево b)

Устаревшее. Начиная с версии 1.1 JDK, заменено на setVisible (логическое).

Размер размер ()

Устаревшее. Начиная с версии 1.1 JDK, заменено getSize ().

Строка toString ()

Возвращает строковое представление этого компонента и его значения.

void TransferFocus ()

Переносит фокус на следующий компонент, как если бы этот компонент был владельцем фокуса.

void TransferFocusBackward ()

Переносит фокус на предыдущий компонент, как если бы этот компонент был владельцем фокуса.

void TransferFocusUpCycle ()

Переносит фокус вверх на один цикл обхода фокуса.

Пустое обновление (Графика г)

Обновляет этот компонент.

void validate ()

Гарантирует, что этот компонент имеет допустимый макет.

Границы прямоугольника ()

Устаревшее. Начиная с версии 1.1 JDK, заменено getBounds ().

защищенное событие AWTEvent coalesceEvents (существующее событие AWTEvent, новое событие AWTEvent)

Потенциально объединить событие, публикуемое с существующим событием.

Защищенная строка paramString ()

Возвращает строку, представляющую состояние этого компонента.

Защищенный void firePropertyChange (String propertyName, int oldValue, int newValue)

Поддержка отчетов об изменениях связанных свойств для целочисленных свойств.

Размер предпочитаемый размер ()

Устаревшее. Начиная с версии 1.1 JDK, заменено на getPreferredSize ().

логическое prepareImage (изображение, обозреватель ImageObserver)

Подготавливает изображение для рендеринга на этом компоненте.

Размер MinimumSize ()

Устаревшее. Начиная с версии 1.1 JDK, заменено getMinimumSize ().

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.lang.Object

java.lang.Object

Класс AWT Label

Вступление

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

Объявление класса

Ниже приводится объявление для класса java.awt.Label :

public class Label
   extends Component
      implements Accessible

поле

Ниже приведены поля для класса java.awt.Component :

  • static int CENTER – указывает, что метка должна быть центрирована.

  • static int LEFT – указывает, что метка должна быть выровнена по левому краю.

  • static int RIGHT – указывает, что метка должна быть правильно выровнена.

static int CENTER – указывает, что метка должна быть центрирована.

static int LEFT – указывает, что метка должна быть выровнена по левому краю.

static int RIGHT – указывает, что метка должна быть правильно выровнена.

Конструкторы классов

SN Конструктор и описание
1

Этикетка()

Создает пустой ярлык.

2

Метка (текст строки)

Создает новую метку с указанной строкой текста, выровненной по левому краю.

3

Метка (текст строки, выравнивание int)

Создает новую метку, которая представляет указанную строку текста с указанным выравниванием.

Этикетка()

Создает пустой ярлык.

Метка (текст строки)

Создает новую метку с указанной строкой текста, выровненной по левому краю.

Метка (текст строки, выравнивание int)

Создает новую метку, которая представляет указанную строку текста с указанным выравниванием.

Методы класса

SN Метод и описание
1

void addNotify ()

Создает одноранговый узел для этого ярлыка.

2

AccessibleContext getAccessibleContext ()

Получает AccessibleContext, связанный с этой меткой.

3

int getAlignment ()

Получает текущее выравнивание этой метки.

4

Строка getText ()

Получает текст этой метки.

5

Защищенная строка paramString ()

Возвращает строку, представляющую состояние этой метки.

6

void setAlignment (int alignment)

Устанавливает выравнивание для этой метки в указанное выравнивание.

7

void setText (String text)

Устанавливает текст для этой метки в указанный текст.

void addNotify ()

Создает одноранговый узел для этого ярлыка.

AccessibleContext getAccessibleContext ()

Получает AccessibleContext, связанный с этой меткой.

int getAlignment ()

Получает текущее выравнивание этой метки.

Строка getText ()

Получает текст этой метки.

Защищенная строка paramString ()

Возвращает строку, представляющую состояние этой метки.

void setAlignment (int alignment)

Устанавливает выравнивание для этой метки в указанное выравнивание.

void setText (String text)

Устанавливает текст для этой метки в указанный текст.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.awt.Component

  • java.lang.Object

java.awt.Component

java.lang.Object

Пример метки

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtControlDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtControlDemo  awtControlDemo = new AwtControlDemo();
      awtControlDemo.showLabelDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showLabelDemo(){
      headerLabel.setText("Control in action: Label");      

      Label label = new Label();
      label.setText("Welcome to TutorialsPoint AWT Tutorial.");
      label.setAlignment(Label.CENTER);
      label.setBackground(Color.GRAY);
      label.setForeground(Color.WHITE);
      controlPanel.add(label);
   
      mainFrame.setVisible(true);  
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Проверьте следующий вывод

AWT Label

AWT Button Class

Вступление

Кнопка является компонентом управления, который имеет метку и генерирует событие при нажатии. Когда кнопка нажата и отпущена, AWT отправляет экземпляр ActionEvent на кнопку, вызывая processEvent для кнопки. Метод processEvent кнопки получает все события для кнопки; он передает событие действия, вызывая свой собственный метод processActionEvent. Последний метод передает событие действия всем слушателям действия, которые зарегистрировали интерес к событиям действия, генерируемым этой кнопкой.

Если приложение хочет выполнить какое-либо действие на основе нажатия и отпускания кнопки, оно должно реализовать ActionListener и зарегистрировать новый прослушиватель для получения событий от этой кнопки, вызывая метод addActionListener кнопки. Приложение может использовать команду действия кнопки в качестве протокола обмена сообщениями.

Объявление класса

Ниже приводится объявление для класса java.awt.Button :

public class Button
   extends Component
      implements Accessible

Конструкторы классов

SN Конструктор и описание
1

Кнопка ()

Создает кнопку с пустой строкой для ее метки.

2

Кнопка (текст строки)

Создает новую кнопку с указанной меткой.

Кнопка ()

Создает кнопку с пустой строкой для ее метки.

Кнопка (текст строки)

Создает новую кнопку с указанной меткой.

Методы класса

SN Метод и описание
1

void addActionListener (ActionListener l)

Добавляет указанный слушатель действия, чтобы получать события действия от этой кнопки.

2

void addNotify ()

Создает узел кнопки.

3

AccessibleContext getAccessibleContext ()

Получает AccessibleContext, связанный с этой кнопкой.

4

Строка getActionCommand ()

Возвращает имя команды события действия, вызванного этой кнопкой.

5

ActionListener [] getActionListeners ()

Возвращает массив всех слушателей действий, зарегистрированных на этой кнопке.

6

Строка getLabel ()

Получает метку этой кнопки.

7

<T расширяет EventListener> T [] getListeners (Класс <T> listenerType)

Возвращает массив всех объектов, зарегистрированных в данный момент как FooListeners для этой кнопки.

8

Защищенная строка paramString ()

Возвращает строку, представляющую состояние этой кнопки.

9

защищенный void processActionEvent (ActionEvent e)

Обрабатывает события действия, возникающие на этой кнопке, путем отправки их всем зарегистрированным объектам ActionListener.

10

Защищенный процесс vEventEvent (AWTEvent e)

Обрабатывает события по этой кнопке.

11

void removeActionListener (ActionListener l)

Удаляет указанный прослушиватель действий, чтобы он больше не получал события действий от этой кнопки.

12

void setActionCommand (команда String)

Устанавливает имя команды для события действия, запускаемого этой кнопкой.

13

void setLabel (String label)

Устанавливает метку кнопки в качестве указанной строки.

void addActionListener (ActionListener l)

Добавляет указанный слушатель действия, чтобы получать события действия от этой кнопки.

void addNotify ()

Создает узел кнопки.

AccessibleContext getAccessibleContext ()

Получает AccessibleContext, связанный с этой кнопкой.

Строка getActionCommand ()

Возвращает имя команды события действия, вызванного этой кнопкой.

ActionListener [] getActionListeners ()

Возвращает массив всех слушателей действий, зарегистрированных на этой кнопке.

Строка getLabel ()

Получает метку этой кнопки.

<T расширяет EventListener> T [] getListeners (Класс <T> listenerType)

Возвращает массив всех объектов, зарегистрированных в данный момент как FooListeners для этой кнопки.

Защищенная строка paramString ()

Возвращает строку, представляющую состояние этой кнопки.

защищенный void processActionEvent (ActionEvent e)

Обрабатывает события действия, возникающие на этой кнопке, путем отправки их всем зарегистрированным объектам ActionListener.

Защищенный процесс vEventEvent (AWTEvent e)

Обрабатывает события по этой кнопке.

void removeActionListener (ActionListener l)

Удаляет указанный прослушиватель действий, чтобы он больше не получал события действий от этой кнопки.

void setActionCommand (команда String)

Устанавливает имя команды для события действия, запускаемого этой кнопкой.

void setLabel (String label)

Устанавливает метку кнопки в качестве указанной строки.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.awt.Component

  • java.lang.Object

java.awt.Component

java.lang.Object

Пример кнопки

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtControlDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtControlDemo  awtControlDemo = new AwtControlDemo();
      awtControlDemo.showButtonDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showButtonDemo(){
      headerLabel.setText("Control in action: Button"); 

      Button okButton = new Button("OK");
      Button submitButton = new Button("Submit");
      Button cancelButton = new Button("Cancel");

      okButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            statusLabel.setText("Ok Button clicked.");
         }
      });

      submitButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            statusLabel.setText("Submit Button clicked.");
         }
      });

      cancelButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            statusLabel.setText("Cancel Button clicked.");
         }
      });

      controlPanel.add(okButton);
      controlPanel.add(submitButton);
      controlPanel.add(cancelButton);       

      mainFrame.setVisible(true);  
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Проверьте следующий вывод

Кнопка AWT

AWT CheckBox Class

Вступление

Флажок используется для включения или выключения опции (true) или выключения (false). Для каждого флажка есть метка, обозначающая его действие. Состояние флажка можно изменить, нажав на него.

Объявление класса

Ниже приводится объявление для класса java.awt.Checkbox :

public class Checkbox
   extends Component
      implements ItemSelectable,Accessible

Конструкторы классов

SN Конструктор и описание
1

Флажок ()

Создает флажок с пустой строкой для своей метки.

2

Флажок (Строковая метка)

Создает флажок с указанной меткой.

3

Флажок (Строковая метка, логическое состояние)

Создает флажок с указанной меткой и устанавливает указанное состояние.

4

Флажок (метка строки, логическое состояние, группа CheckboxGroup)

Создает флажок с указанной меткой, установленным в указанное состояние и в указанной группе флажков.

5

Флажок (метка строки, группа CheckboxGroup, логическое состояние)

Создает флажок с указанной меткой в ​​указанной группе флажков и устанавливается в указанное состояние.

Флажок ()

Создает флажок с пустой строкой для своей метки.

Флажок (Строковая метка)

Создает флажок с указанной меткой.

Флажок (Строковая метка, логическое состояние)

Создает флажок с указанной меткой и устанавливает указанное состояние.

Флажок (метка строки, логическое состояние, группа CheckboxGroup)

Создает флажок с указанной меткой, установленным в указанное состояние и в указанной группе флажков.

Флажок (метка строки, группа CheckboxGroup, логическое состояние)

Создает флажок с указанной меткой в ​​указанной группе флажков и устанавливается в указанное состояние.

Методы класса

SN Метод и описание
1

void addItemListener (ItemListener l)

Добавляет прослушиватель указанного элемента для получения событий элемента из этого флажка.

2

void addNotify ()

Создает узел флажка.

3

AccessibleContext getAccessibleContext ()

Получает AccessibleContext, связанный с этим флажком.

4

CheckboxGroup getCheckboxGroup ()

Определяет группу этого флажка.

5

ItemListener [] getItemListeners ()

Возвращает массив всех прослушивателей элементов, зарегистрированных в этом флажке.

6

Строка getLabel ()

Получает метку этого флажка.

7

<T расширяет EventListener> T [] getListeners (Класс <T> listenerType)

Возвращает массив всех объектов, зарегистрированных в настоящее время как FooListeners на этом флажке.

8

Object [] getSelectedObjects ()

Возвращает массив (длина 1), содержащий метку флажка или ноль, если флажок не установлен.

9

логическое getState ()

Определяет, находится ли этот флажок во включенном или выключенном состоянии.

10

Защищенная строка paramString ()

Возвращает строку, представляющую состояние этого флажка.

11

Защищенный процесс vEventEvent (AWTEvent e)

Обрабатывает события в этом флажке.

12

защищенный void processItemEvent (ItemEvent e)

Обрабатывает события элемента, происходящие в этом флажке, отправляя их всем зарегистрированным объектам ItemListener.

13

void removeItemListener (ItemListener l)

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

14

void setCheckboxGroup (CheckboxGroup g)

Устанавливает группу этого флажка в указанную группу флажка.

15

void setLabel (String label)

Устанавливает метку этого флажка в качестве строкового аргумента.

16

void setState (логическое состояние)

Устанавливает состояние этого флажка в указанное состояние.

void addItemListener (ItemListener l)

Добавляет прослушиватель указанного элемента для получения событий элемента из этого флажка.

void addNotify ()

Создает узел флажка.

AccessibleContext getAccessibleContext ()

Получает AccessibleContext, связанный с этим флажком.

CheckboxGroup getCheckboxGroup ()

Определяет группу этого флажка.

ItemListener [] getItemListeners ()

Возвращает массив всех прослушивателей элементов, зарегистрированных в этом флажке.

Строка getLabel ()

Получает метку этого флажка.

<T расширяет EventListener> T [] getListeners (Класс <T> listenerType)

Возвращает массив всех объектов, зарегистрированных в настоящее время как FooListeners на этом флажке.

Object [] getSelectedObjects ()

Возвращает массив (длина 1), содержащий метку флажка или ноль, если флажок не установлен.

логическое getState ()

Определяет, находится ли этот флажок во включенном или выключенном состоянии.

Защищенная строка paramString ()

Возвращает строку, представляющую состояние этого флажка.

Защищенный процесс vEventEvent (AWTEvent e)

Обрабатывает события в этом флажке.

защищенный void processItemEvent (ItemEvent e)

Обрабатывает события элемента, происходящие в этом флажке, отправляя их всем зарегистрированным объектам ItemListener.

void removeItemListener (ItemListener l)

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

void setCheckboxGroup (CheckboxGroup g)

Устанавливает группу этого флажка в указанную группу флажка.

void setLabel (String label)

Устанавливает метку этого флажка в качестве строкового аргумента.

void setState (логическое состояние)

Устанавливает состояние этого флажка в указанное состояние.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.awt.Component

  • java.lang.Object

java.awt.Component

java.lang.Object

Пример CheckBox

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtControlDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtControlDemo  awtControlDemo = new AwtControlDemo();
      awtControlDemo.showCheckBoxDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showCheckBoxDemo(){

      headerLabel.setText("Control in action: CheckBox"); 

      Checkbox chkApple = new Checkbox("Apple");
      Checkbox chkMango = new Checkbox("Mango");
      Checkbox chkPeer = new Checkbox("Peer");


      chkApple.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {             
            statusLabel.setText("Apple Checkbox: " 
            + (e.getStateChange()==1?"checked":"unchecked"));
         }
      });

      chkMango.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            statusLabel.setText("Mango Checkbox: " 
            + (e.getStateChange()==1?"checked":"unchecked"));
         }
      });

      chkPeer.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            statusLabel.setText("Peer Checkbox: " 
            + (e.getStateChange()==1?"checked":"unchecked"));
         }
      });

      controlPanel.add(chkApple);
      controlPanel.add(chkMango);
      controlPanel.add(chkPeer);       

      mainFrame.setVisible(true);  
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Проверьте следующий вывод

AWT CheckBox

AWT CheckBoxGroup Class

Вступление

Класс CheckboxGroup используется для группировки набора флажков.

Объявление класса

Ниже приводится объявление для класса java.awt.CheckboxGroup :

public class CheckboxGroup
   extends Object
      implements Serializable

Конструкторы классов

SN Конструктор и описание
1

CheckboxGroup () ()

Создает новый экземпляр CheckboxGroup.

CheckboxGroup () ()

Создает новый экземпляр CheckboxGroup.

Методы класса

SN Метод и описание
1

Флажок getCurrent ()

Устаревшее. Начиная с версии 1.1 JDK, заменено getSelectedCheckbox ().

2

Флажок getSelectedCheckbox ()

Получает текущий выбор из этой группы флажков.

3

void setCurrent (флажок)

Устаревшее. Начиная с версии 1.1 JDK, заменено на setSelectedCheckbox (флажок).

4

void setSelectedCheckbox (флажок)

Устанавливает текущий выбранный флажок в этой группе, чтобы быть указанным флажком.

5

Строка toString ()

Возвращает строковое представление этой группы флажков, включая значение ее текущего выбора.

Флажок getCurrent ()

Устаревшее. Начиная с версии 1.1 JDK, заменено getSelectedCheckbox ().

Флажок getSelectedCheckbox ()

Получает текущий выбор из этой группы флажков.

void setCurrent (флажок)

Устаревшее. Начиная с версии 1.1 JDK, заменено на setSelectedCheckbox (флажок).

void setSelectedCheckbox (флажок)

Устанавливает текущий выбранный флажок в этой группе, чтобы быть указанным флажком.

Строка toString ()

Возвращает строковое представление этой группы флажков, включая значение ее текущего выбора.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.lang.Object

java.lang.Object

Пример CheckBoxGroup

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtControlDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtControlDemo  awtControlDemo = new AwtControlDemo();
      awtControlDemo.showCheckBoxGroupDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showCheckBoxGroupDemo(){
    
      headerLabel.setText("Control in action: CheckBoxGroup"); 

      CheckboxGroup fruitGroup = new CheckboxGroup();

      Checkbox chkApple = new Checkbox("Apple",fruitGroup,true);
      Checkbox chkMango = new Checkbox("Mango",fruitGroup,false);
      Checkbox chkPeer = new Checkbox("Peer",fruitGroup,false);

      statusLabel.setText("Apple Checkbox: checked");
      chkApple.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {             
            statusLabel.setText("Apple Checkbox: checked");
         }
      });

      chkMango.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            statusLabel.setText("Mango Checkbox: checked");
         }
      });

      chkPeer.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            statusLabel.setText("Peer Checkbox: checked");
         }
      });

      controlPanel.add(chkApple);
      controlPanel.add(chkMango);   
      controlPanel.add(chkPeer);       

      mainFrame.setVisible(true);  
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Проверьте следующий вывод

AWT CheckBoxGroup

AWT List Class

Вступление

Список представляет собой список текстовых элементов. Список может быть настроен так, что пользователь может выбрать либо один элемент, либо несколько элементов.

Объявление класса

Ниже приводится объявление для класса java.awt.List :

public class List
   extends Component
      implements ItemSelectable, Accessible

Конструкторы классов

SN Конструктор и описание
1

Список()

Создает новый список прокрутки.

2

Список (целые строки)

Создает новый список прокрутки, инициализированный указанным количеством видимых строк.

3

Список (int row, логический множественный режим)

Создает новый список прокрутки, инициализированный для отображения указанного количества строк.

Список()

Создает новый список прокрутки.

Список (целые строки)

Создает новый список прокрутки, инициализированный указанным количеством видимых строк.

Список (int row, логический множественный режим)

Создает новый список прокрутки, инициализированный для отображения указанного количества строк.

Методы класса

<T расширяет EventListener> T [] getListeners (Класс <T> listenerType)

Возвращает массив всех объектов, зарегистрированных в настоящее время как FooListeners в этом списке.

SN Метод и описание
1

void add (строковый элемент)

Добавляет указанный элемент в конец списка прокрутки.

2

void add (строковый элемент, индекс int)

Добавляет указанный элемент в список прокрутки в позиции, указанной индексом.

3

void addActionListener (ActionListener l)

Добавляет указанный слушатель действия для получения событий действия из этого списка.

4

void addItem (элемент String)

Устаревшее. заменяется на add (String).

5

void addItem (строковый элемент, индекс int)

Устаревшее. заменяется на add (String, int).

6

void addItemListener (ItemListener l)

Добавляет прослушиватель указанного элемента для получения событий элемента из этого списка.

7

void addNotify ()

Создает одноранговый узел для списка.

8

логическое разрешениеMultipleSelections ()

Устаревшее. Начиная с версии 1.1 JDK, заменено isMultipleMode ().

9

void clear ()

Устаревшее. Начиная с версии 1.1 JDK, заменено на removeAll ().

10

int countItems ()

Устаревшее. Начиная с версии 1.1 JDK, заменено getItemCount ().

11

void delItem (int position)

Устаревшее. заменить на удалить (String) и удалить (int).

12

void delItems(int start, int end)

Устаревшее. As of JDK version 1.1, Not for public use in the future. This method is expected to be retained only as a package private method.

13

void deselect(int index)

Отмена выбора элемента по указанному индексу.

14

AccessibleContext getAccessibleContext()

Gets the AccessibleContext associated with this List.

15

ActionListener[] getActionListeners()

Returns an array of all the action listeners registered on this list.

16

String getItem(int index)

Gets the item associated with the specified index.

17

int getItemCount()

Gets the number of items in the list.

18

ItemListener[] getItemListeners()

Returns an array of all the item listeners registered on this list.

19

String[] getItems()

Gets the items in the list.

20

Dimension getMinimumSize()

Determines the minimum size of this scrolling list.

21

Dimension getMinimumSize(int rows)

Gets the minumum dimensions for a list with the specified number of rows.

22

Dimension getPreferredSize()

Gets the preferred size of this scrolling list.

23

Dimension getPreferredSize(int rows)

Gets the preferred dimensions for a list with the specified number of rows.

24

int getRows()

Gets the number of visible lines in this list.

25

int getSelectedIndex()

Gets the index of the selected item on the list,

26

int[] getSelectedIndexes()

Gets the selected indexes on the list.

27

String getSelectedItem()

Gets the selected item on this scrolling list.

28

String[] getSelectedItems()

Gets the selected items on this scrolling list.

29

Object[] getSelectedObjects()

Gets the selected items on this scrolling list in an array of Objects.

30

int getVisibleIndex()

Gets the index of the item that was last made visible by the method makeVisible.

31

boolean isIndexSelected(int index)

Determines if the specified item in this scrolling list is selected.

32

boolean isMultipleMode()

Determines whether this list allows multiple selections.

33

boolean isSelected(int index)

Устаревшее. As of JDK version 1.1, replaced by isIndexSelected(int).

34

void makeVisible(int index)

Makes the item at the specified index visible.

35

Dimension minimumSize()

Устаревшее. As of JDK version 1.1, replaced by getMinimumSize().

36

Dimension minimumSize(int rows)

Устаревшее. As of JDK version 1.1, replaced by getMinimumSize(int).

37

protected String paramString()

Returns the parameter string representing the state of this scrolling list.

38

Dimension preferredSize()

Устаревшее. As of JDK version 1.1, replaced by getPreferredSize().

39

Dimension preferredSize(int rows)

Устаревшее. As of JDK version 1.1, replaced by getPreferredSize(int).

40

protected void processActionEvent(ActionEvent e)

Processes action events occurring on this component by dispatching them to any registered ActionListener objects.

41

protected void processEvent(AWTEvent e)

Processes events on this scrolling list.

42

protected void processItemEvent(ItemEvent e)

Processes item events occurring on this list by dispatching them to any registered ItemListener objects.

43

void remove(int position)

Removes the item at the specified position from this scrolling list.

44

void remove(String item)

Removes the first occurrence of an item from the list.

45

void removeActionListener(ActionListener l)

Removes the specified action listener so that it no longer receives action events from this list.

46

void removeAll()

Removes all items from this list.

47

void removeItemListener(ItemListener l)

Removes the specified item listener so that it no longer receives item events from this list.

48

void removeNotify()

Removes the peer for this list.

49

void replaceItem(String newValue, int index)

Replaces the item at the specified index in the scrolling list with the new string.

50

void select(int index)

Selects the item at the specified index in the scrolling list.

51

void setMultipleMode(boolean b)

Sets the flag that determines whether this list allows multiple selections.

52

void setMultipleSelections(boolean b)

Устаревшее. As of JDK version 1.1, replaced by setMultipleMode(boolean).

void add (строковый элемент)

Добавляет указанный элемент в конец списка прокрутки.

void add (строковый элемент, индекс int)

Добавляет указанный элемент в список прокрутки в позиции, указанной индексом.

void addActionListener (ActionListener l)

Добавляет указанный слушатель действия для получения событий действия из этого списка.

void addItem (элемент String)

Устаревшее. заменяется на add (String).

void addItem (строковый элемент, индекс int)

Устаревшее. заменяется на add (String, int).

void addItemListener (ItemListener l)

Добавляет прослушиватель указанного элемента для получения событий элемента из этого списка.

void addNotify ()

Создает одноранговый узел для списка.

логическое разрешениеMultipleSelections ()

Устаревшее. Начиная с версии 1.1 JDK, заменено isMultipleMode ().

void clear ()

Устаревшее. Начиная с версии 1.1 JDK, заменено на removeAll ().

int countItems ()

Устаревшее. Начиная с версии 1.1 JDK, заменено getItemCount ().

void delItem (int position)

Устаревшее. заменить на удалить (String) и удалить (int).

void delItems(int start, int end)

Устаревшее. As of JDK version 1.1, Not for public use in the future. This method is expected to be retained only as a package private method.

void deselect(int index)

Отмена выбора элемента по указанному индексу.

AccessibleContext getAccessibleContext()

Gets the AccessibleContext associated with this List.

ActionListener[] getActionListeners()

Returns an array of all the action listeners registered on this list.

String getItem(int index)

Gets the item associated with the specified index.

int getItemCount()

Gets the number of items in the list.

ItemListener[] getItemListeners()

Returns an array of all the item listeners registered on this list.

String[] getItems()

Gets the items in the list.

Dimension getMinimumSize()

Determines the minimum size of this scrolling list.

Dimension getMinimumSize(int rows)

Gets the minumum dimensions for a list with the specified number of rows.

Dimension getPreferredSize()

Gets the preferred size of this scrolling list.

Dimension getPreferredSize(int rows)

Gets the preferred dimensions for a list with the specified number of rows.

int getRows()

Gets the number of visible lines in this list.

int getSelectedIndex()

Gets the index of the selected item on the list,

int[] getSelectedIndexes()

Gets the selected indexes on the list.

String getSelectedItem()

Gets the selected item on this scrolling list.

String[] getSelectedItems()

Gets the selected items on this scrolling list.

Object[] getSelectedObjects()

Gets the selected items on this scrolling list in an array of Objects.

int getVisibleIndex()

Gets the index of the item that was last made visible by the method makeVisible.

boolean isIndexSelected(int index)

Determines if the specified item in this scrolling list is selected.

boolean isMultipleMode()

Determines whether this list allows multiple selections.

boolean isSelected(int index)

Устаревшее. As of JDK version 1.1, replaced by isIndexSelected(int).

void makeVisible(int index)

Makes the item at the specified index visible.

Dimension minimumSize()

Устаревшее. As of JDK version 1.1, replaced by getMinimumSize().

Dimension minimumSize(int rows)

Устаревшее. As of JDK version 1.1, replaced by getMinimumSize(int).

protected String paramString()

Returns the parameter string representing the state of this scrolling list.

Dimension preferredSize()

Устаревшее. As of JDK version 1.1, replaced by getPreferredSize().

Dimension preferredSize(int rows)

Устаревшее. As of JDK version 1.1, replaced by getPreferredSize(int).

protected void processActionEvent(ActionEvent e)

Processes action events occurring on this component by dispatching them to any registered ActionListener objects.

protected void processEvent(AWTEvent e)

Processes events on this scrolling list.

protected void processItemEvent(ItemEvent e)

Processes item events occurring on this list by dispatching them to any registered ItemListener objects.

void remove(int position)

Removes the item at the specified position from this scrolling list.

void remove(String item)

Removes the first occurrence of an item from the list.

void removeActionListener(ActionListener l)

Removes the specified action listener so that it no longer receives action events from this list.

void removeAll()

Removes all items from this list.

void removeItemListener(ItemListener l)

Removes the specified item listener so that it no longer receives item events from this list.

void removeNotify()

Removes the peer for this list.

void replaceItem(String newValue, int index)

Replaces the item at the specified index in the scrolling list with the new string.

void select(int index)

Selects the item at the specified index in the scrolling list.

void setMultipleMode(boolean b)

Sets the flag that determines whether this list allows multiple selections.

void setMultipleSelections(boolean b)

Устаревшее. As of JDK version 1.1, replaced by setMultipleMode(boolean).

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.awt.Component

  • java.lang.Object

java.awt.Component

java.lang.Object

List Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtControlDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtControlDemo  awtControlDemo = new AwtControlDemo();
      awtControlDemo.showListDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showListDemo(){                                       

      headerLabel.setText("Control in action: List"); 
      final List fruitList = new List(4,false);

      fruitList.add("Apple");
      fruitList.add("Grapes");
      fruitList.add("Mango");
      fruitList.add("Peer");

      final List vegetableList = new List(4,true);
   
      vegetableList.add("Lady Finger");
      vegetableList.add("Onion");
      vegetableList.add("Potato");
      vegetableList.add("Tomato");

      Button showButton = new Button("Show");

      showButton.addActionListener(new ActionListener() {

         public void actionPerformed(ActionEvent e) {     
            String data = "Fruits Selected: " 
               + fruitList.getItem(fruitList.getSelectedIndex());
            data += ", Vegetables selected: ";
            for(String vegetable:vegetableList.getSelectedItems()){
               data += vegetable + " ";
            }
            statusLabel.setText(data);
         }
      }); 

      controlPanel.add(fruitList);
      controlPanel.add(vegetableList);
      controlPanel.add(showButton);

      mainFrame.setVisible(true);  
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Проверьте следующий вывод

AWT List

AWT TextField Class

Вступление

The textField component allows the user to edit single line of text.When the user types a key in the text field the event is sent to the TextField. The key event may be key pressed, Key released or key typed. The key event is passed to the registered KeyListener. It is also possible to for an ActionEvent if the ActionEvent is enabled on the textfield then ActionEvent may be fired by pressing the return key.

Объявление класса

Following is the declaration for java.awt.TextField class:

public class TextField
   extends TextComponent

Конструкторы классов

SN Конструктор и описание
1

TextField()

Constructs a new text field.

2

TextField(int columns)

Constructs a new empty text field with the specified number of columns.

3

TextField(String text)

Constructs a new text field initialized with the specified text.

4

TextField(String text, int columns)

Constructs a new text field initialized with the specified text to be displayed, and wide enough to hold the specified number of columns.

TextField()

Constructs a new text field.

TextField(int columns)

Constructs a new empty text field with the specified number of columns.

TextField(String text)

Constructs a new text field initialized with the specified text.

TextField(String text, int columns)

Constructs a new text field initialized with the specified text to be displayed, and wide enough to hold the specified number of columns.

Методы класса

SN Метод и описание
1

void addActionListener(ActionListener l)

Adds the specified action listener to receive action events from this text field.

2

void addNotify()

Creates the TextField’s peer.

3

boolean echoCharIsSet()

Indicates whether or not this text field has a character set for echoing.

4

AccessibleContext getAccessibleContext()

Gets the AccessibleContext associated with this TextField.

5

ActionListener[] getActionListeners()

Returns an array of all the action listeners registered on this textfield.

6

int getColumns()

Gets the number of columns in this text field.

7

char getEchoChar()

Gets the character that is to be used for echoing.

8

<T extends EventListener> T[] getListeners(Class<T> listenerType)

Returns an array of all the objects currently registered as FooListeners upon this TextField.

9

Dimension getMinimumSize()

Gets the minumum dimensions for this text field.

10

Dimension getMinimumSize(int columns) Gets the minumum dimensions for a text field with the specified number of columns.

11

Dimension getPreferredSize()

Gets the preferred size of this text field.

12

Dimension getPreferredSize(int columns)

Gets the preferred size of this text field with the specified number of columns.

13

Dimension minimumSize()

Устаревшее. As of JDK version 1.1, replaced by getMinimumSize().

14

Dimension minimumSize(int columns)

Устаревшее. As of JDK version 1.1, replaced by getMinimumSize(int).

15

protected String paramString()

Returns a string representing the state of this TextField.

16

Dimension preferredSize()

Устаревшее. As of JDK version 1.1, replaced by getPreferredSize().

17

Dimension preferredSize(int columns)

Устаревшее. As of JDK version 1.1, replaced by getPreferredSize(int).

18

protected void processActionEvent(ActionEvent e)

Processes action events occurring on this text field by dispatching them to any registered ActionListener objects.

19

protected void processEvent(AWTEvent e)

Processes events on this text field.

20

void removeActionListener(ActionListener l)

Removes the specified action listener so that it no longer receives action events from this text field.

21

void setColumns(int columns)

Sets the number of columns in this text field.

22

void setEchoChar(char c)

Sets the echo character for this text field.

23

void setEchoCharacter(char c)

Устаревшее. As of JDK version 1.1, replaced by setEchoChar(char).

24

void setText(String t)

Sets the text that is presented by this text component to be the specified text.

void addActionListener(ActionListener l)

Adds the specified action listener to receive action events from this text field.

void addNotify()

Creates the TextField’s peer.

boolean echoCharIsSet()

Indicates whether or not this text field has a character set for echoing.

AccessibleContext getAccessibleContext()

Gets the AccessibleContext associated with this TextField.

ActionListener[] getActionListeners()

Returns an array of all the action listeners registered on this textfield.

int getColumns()

Gets the number of columns in this text field.

char getEchoChar()

Gets the character that is to be used for echoing.

<T extends EventListener> T[] getListeners(Class<T> listenerType)

Returns an array of all the objects currently registered as FooListeners upon this TextField.

Dimension getMinimumSize()

Gets the minumum dimensions for this text field.

Dimension getMinimumSize(int columns) Gets the minumum dimensions for a text field with the specified number of columns.

Dimension getPreferredSize()

Gets the preferred size of this text field.

Dimension getPreferredSize(int columns)

Gets the preferred size of this text field with the specified number of columns.

Dimension minimumSize()

Устаревшее. As of JDK version 1.1, replaced by getMinimumSize().

Dimension minimumSize(int columns)

Устаревшее. As of JDK version 1.1, replaced by getMinimumSize(int).

protected String paramString()

Returns a string representing the state of this TextField.

Dimension preferredSize()

Устаревшее. As of JDK version 1.1, replaced by getPreferredSize().

Dimension preferredSize(int columns)

Устаревшее. As of JDK version 1.1, replaced by getPreferredSize(int).

protected void processActionEvent(ActionEvent e)

Processes action events occurring on this text field by dispatching them to any registered ActionListener objects.

protected void processEvent(AWTEvent e)

Processes events on this text field.

void removeActionListener(ActionListener l)

Removes the specified action listener so that it no longer receives action events from this text field.

void setColumns(int columns)

Sets the number of columns in this text field.

void setEchoChar(char c)

Sets the echo character for this text field.

void setEchoCharacter(char c)

Устаревшее. As of JDK version 1.1, replaced by setEchoChar(char).

void setText(String t)

Sets the text that is presented by this text component to be the specified text.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.awt.TextComponent

  • java.awt.Component

  • java.lang.Object

java.awt.TextComponent

java.awt.Component

java.lang.Object

TextField Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtControlDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtControlDemo  awtControlDemo = new AwtControlDemo();
      awtControlDemo.showTextFieldDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showTextFieldDemo(){
      headerLabel.setText("Control in action: TextField"); 

      Label  namelabel= new Label("User ID: ", Label.RIGHT);
      Label  passwordLabel = new Label("Password: ", Label.CENTER);
      final TextField userText = new TextField(6);
      final TextField passwordText = new TextField(6);
      passwordText.setEchoChar('*');

      Button loginButton = new Button("Login");
   
      loginButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {     
            String data = "Username: " + userText.getText();
            data += ", Password: " + passwordText.getText();
            statusLabel.setText(data);        
         }
      }); 

      controlPanel.add(namelabel);
      controlPanel.add(userText);
      controlPanel.add(passwordLabel);       
      controlPanel.add(passwordText);
      controlPanel.add(loginButton);
      mainFrame.setVisible(true);  
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Проверьте следующий вывод

AWT TextField

AWT TextArea Class

Вступление

The TextArea control in AWT provide us multiline editor area. The user can type here as much as he wants. When the text in the text area become larger than the viewable area the scroll bar is automatically appears which help us to scroll the text up & down and right & left.

Объявление класса

Following is the declaration for java.awt.TextArea class:

public class TextArea
   extends TextComponent

поле

Following are the fields for java.awt.TextArea class:

  • static int SCROLLBARS_BOTH — Create and display both vertical and horizontal scrollbars.

  • static int SCROLLBARS_HORIZONTAL_ONLY — Create and display horizontal scrollbar only.

  • static int SCROLLBARS_NONE — Do not create or display any scrollbars for the text area.

  • static int SCROLLBARS_VERTICAL_ONLY — Create and display vertical scrollbar only.

static int SCROLLBARS_BOTH — Create and display both vertical and horizontal scrollbars.

static int SCROLLBARS_HORIZONTAL_ONLY — Create and display horizontal scrollbar only.

static int SCROLLBARS_NONE — Do not create or display any scrollbars for the text area.

static int SCROLLBARS_VERTICAL_ONLY — Create and display vertical scrollbar only.

Конструкторы классов

SN Конструктор и описание
1

TextArea()

Constructs a new text area with the empty string as text.

2

TextArea(int rows, int columns)

Constructs a new text area with the specified number of rows and columns and the empty string as text.

3

TextArea(String text)

Constructs a new text area with the specified text.

4

TextArea(String text, int rows, int columns)

Constructs a new text area with the specified text, and with the specified number of rows and columns.

5

TextArea(String text, int rows, int columns, int scrollbars)

Constructs a new text area with the specified text, and with the rows, columns, and scroll bar visibility as specified.

TextArea()

Constructs a new text area with the empty string as text.

TextArea(int rows, int columns)

Constructs a new text area with the specified number of rows and columns and the empty string as text.

TextArea(String text)

Constructs a new text area with the specified text.

TextArea(String text, int rows, int columns)

Constructs a new text area with the specified text, and with the specified number of rows and columns.

TextArea(String text, int rows, int columns, int scrollbars)

Constructs a new text area with the specified text, and with the rows, columns, and scroll bar visibility as specified.

Методы класса

SN Метод и описание
1

void addNotify()

Creates the TextArea’s peer.

2

void append(String str)

Appends the given text to the text area’s current text.

3

void appendText(String str)

Устаревшее. As of JDK version 1.1, replaced by append(String).

4

AccessibleContext getAccessibleContext()

Returns the AccessibleContext associated with this TextArea.

5

int getColumns()

Returns the number of columns in this text area.

6

Dimension getMinimumSize()

Determines the minimum size of this text area.

7

Dimension getMinimumSize(int rows, int columns)

Determines the minimum size of a text area with the specified number of rows and columns.

8

Dimension getPreferredSize()

Determines the preferred size of this text area.

9

Dimension getPreferredSize(int rows, int columns)

Determines the preferred size of a text area with the specified number of rows and columns.

10

int getRows()

Returns the number of rows in the text area.

11

int getScrollbarVisibility()

Returns an enumerated value that indicates which scroll bars the text area uses.

12

void insert(String str, int pos)

Inserts the specified text at the specified position in this text area.

13

void insertText(String str, int pos)

Устаревшее. As of JDK version 1.1, replaced by insert(String, int).

14

Dimension minimumSize()

Устаревшее. As of JDK version 1.1, replaced by getMinimumSize().

15

Dimension minimumSize(int rows, int columns)

Устаревшее. As of JDK version 1.1, replaced by getMinimumSize(int, int).

16

protected String paramString()

Returns a string representing the state of this TextArea.

17

Dimension preferredSize()

Устаревшее. As of JDK version 1.1, replaced by getPreferredSize().

18

Dimension preferredSize(int rows, int columns)

Устаревшее. As of JDK version 1.1, replaced by getPreferredSize(int, int).

19

void replaceRange(String str, int start, int end)

Replaces text between the indicated start and end positions with the specified replacement text.

20

void replaceText(String str, int start, int end)

Устаревшее. As of JDK version 1.1, replaced by replaceRange(String, int, int).

21

void setColumns(int columns)

Sets the number of columns for this text area.

22

void setRows(int rows)

Sets the number of rows for this text area.

void addNotify()

Creates the TextArea’s peer.

void append(String str)

Appends the given text to the text area’s current text.

void appendText(String str)

Устаревшее. As of JDK version 1.1, replaced by append(String).

AccessibleContext getAccessibleContext()

Returns the AccessibleContext associated with this TextArea.

int getColumns()

Returns the number of columns in this text area.

Dimension getMinimumSize()

Determines the minimum size of this text area.

Dimension getMinimumSize(int rows, int columns)

Determines the minimum size of a text area with the specified number of rows and columns.

Dimension getPreferredSize()

Determines the preferred size of this text area.

Dimension getPreferredSize(int rows, int columns)

Determines the preferred size of a text area with the specified number of rows and columns.

int getRows()

Returns the number of rows in the text area.

int getScrollbarVisibility()

Returns an enumerated value that indicates which scroll bars the text area uses.

void insert(String str, int pos)

Inserts the specified text at the specified position in this text area.

void insertText(String str, int pos)

Устаревшее. As of JDK version 1.1, replaced by insert(String, int).

Dimension minimumSize()

Устаревшее. As of JDK version 1.1, replaced by getMinimumSize().

Dimension minimumSize(int rows, int columns)

Устаревшее. As of JDK version 1.1, replaced by getMinimumSize(int, int).

protected String paramString()

Returns a string representing the state of this TextArea.

Dimension preferredSize()

Устаревшее. As of JDK version 1.1, replaced by getPreferredSize().

Dimension preferredSize(int rows, int columns)

Устаревшее. As of JDK version 1.1, replaced by getPreferredSize(int, int).

void replaceRange(String str, int start, int end)

Replaces text between the indicated start and end positions with the specified replacement text.

void replaceText(String str, int start, int end)

Устаревшее. As of JDK version 1.1, replaced by replaceRange(String, int, int).

void setColumns(int columns)

Sets the number of columns for this text area.

void setRows(int rows)

Sets the number of rows for this text area.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.awt.TextComponent

  • java.awt.Component

  • java.lang.Object

java.awt.TextComponent

java.awt.Component

java.lang.Object

TextArea Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtControlDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtControlDemo  awtControlDemo = new AwtControlDemo();
      awtControlDemo.showTextAreaDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showTextAreaDemo(){
      headerLabel.setText("Control in action: TextArea"); 

      Label  commentlabel= new Label("Comments: ", Label.RIGHT);

      final TextArea commentTextArea = new TextArea("This is a AWT tutorial "
      +"to make GUI application in Java.",5,30);

      Button showButton = new Button("Show");

      showButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {     
            statusLabel.setText( commentTextArea.getText());        
         }
      }); 

      controlPanel.add(commentlabel);
      controlPanel.add(commentTextArea);        
      controlPanel.add(showButton);
      mainFrame.setVisible(true);  
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Проверьте следующий вывод

AWT TextArea

AWT Choice Class

Вступление

Choice control is used to show pop up menu of choices. Выбранный вариант отображается в верхней части меню.

Объявление класса

Following is the declaration for java.awt.Choice class:

public class Choice
   extends Component
      implements ItemSelectable, Accessible

Конструкторы классов

SN Конструктор и описание
1

Choice() ()

Creates a new choice menu.

Choice() ()

Creates a new choice menu.

Методы класса

SN Метод и описание
1

void add(String item)

Adds an item to this Choice menu.

2

void addItem(String item)

Obsolete as of Java 2 platform v1.1.

3

void addItemListener(ItemListener l)

Adds the specified item listener to receive item events from this Choice menu.

4

void addNotify()

Creates the Choice’s peer.

5

int countItems()

Устаревшее. As of JDK version 1.1, replaced by getItemCount().

6

AccessibleContext getAccessibleContext()

Gets the AccessibleContext associated with this Choice.

7

String getItem(int index)

Gets the string at the specified index in this Choice menu.

8

int getItemCount()

Returns the number of items in this Choice menu.

9

ItemListener[] getItemListeners()

Returns an array of all the item listeners registered on this choice.

10

<T extends EventListener> T[] getListeners(Class<T> listenerType)

Returns an array of all the objects currently registered as FooListeners upon this Choice.

11

int getSelectedIndex()

Returns the index of the currently selected item.

12

String getSelectedItem()

Gets a representation of the current choice as a string.

13

Object[] getSelectedObjects()

Returns an array (length 1) containing the currently selected item.

14

void insert(String item, int index)

Inserts the item into this choice at the specified position.

15

protected String paramString()

Returns a string representing the state of this Choice menu.

16

protected void processEvent(AWTEvent e)

Processes events on this choice.

17

protected void processItemEvent(ItemEvent e)

Processes item events occurring on this Choice menu by dispatching them to any registered ItemListener objects.

18

void remove(int position)

Removes an item from the choice menu at the specified position.

19

void remove(String item)

Removes the first occurrence of item from the Choice menu.

20

void removeAll()

Removes all items from the choice menu.

21

void removeItemListener(ItemListener l)

Removes the specified item listener so that it no longer receives item events from this Choice menu.

22

void select(int pos)

Sets the selected item in this Choice menu to be the item at the specified position.

23

void select(String str)

Sets the selected item in this Choice menu to be the item whose name is equal to the specified string.

void add(String item)

Adds an item to this Choice menu.

void addItem(String item)

Obsolete as of Java 2 platform v1.1.

void addItemListener(ItemListener l)

Adds the specified item listener to receive item events from this Choice menu.

void addNotify()

Creates the Choice’s peer.

int countItems()

Устаревшее. As of JDK version 1.1, replaced by getItemCount().

AccessibleContext getAccessibleContext()

Gets the AccessibleContext associated with this Choice.

String getItem(int index)

Gets the string at the specified index in this Choice menu.

int getItemCount()

Returns the number of items in this Choice menu.

ItemListener[] getItemListeners()

Returns an array of all the item listeners registered on this choice.

<T extends EventListener> T[] getListeners(Class<T> listenerType)

Returns an array of all the objects currently registered as FooListeners upon this Choice.

int getSelectedIndex()

Returns the index of the currently selected item.

String getSelectedItem()

Gets a representation of the current choice as a string.

Object[] getSelectedObjects()

Returns an array (length 1) containing the currently selected item.

void insert(String item, int index)

Inserts the item into this choice at the specified position.

protected String paramString()

Returns a string representing the state of this Choice menu.

protected void processEvent(AWTEvent e)

Processes events on this choice.

protected void processItemEvent(ItemEvent e)

Processes item events occurring on this Choice menu by dispatching them to any registered ItemListener objects.

void remove(int position)

Removes an item from the choice menu at the specified position.

void remove(String item)

Removes the first occurrence of item from the Choice menu.

void removeAll()

Removes all items from the choice menu.

void removeItemListener(ItemListener l)

Removes the specified item listener so that it no longer receives item events from this Choice menu.

void select(int pos)

Sets the selected item in this Choice menu to be the item at the specified position.

void select(String str)

Sets the selected item in this Choice menu to be the item whose name is equal to the specified string.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.awt.Component

  • java.lang.Object

java.awt.Component

java.lang.Object

Choice Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtControlDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtControlDemo  awtControlDemo = new AwtControlDemo();
      awtControlDemo.showChoiceDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showChoiceDemo(){                                       

      headerLabel.setText("Control in action: Choice"); 
      final Choice fruitChoice = new Choice();

      fruitChoice.add("Apple");
      fruitChoice.add("Grapes");
      fruitChoice.add("Mango");
      fruitChoice.add("Peer");

      Button showButton = new Button("Show");

      showButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {     
            String data = "Fruit Selected: " 
            + fruitChoice.getItem(fruitChoice.getSelectedIndex());
            statusLabel.setText(data);
         }
      }); 

      controlPanel.add(fruitChoice);
      controlPanel.add(showButton);

      mainFrame.setVisible(true);  
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Проверьте следующий вывод

AWT Choice

AWT Canvas Class

Вступление

Canvas control represents a rectangular area where application can draw something or can receive inputs created by user.

Объявление класса

Following is the declaration for java.awt.Canvas class:

public class Canvas
   extends Component
      implements Accessible

Конструкторы классов

SN Конструктор и описание
1

Canvas()

Constructs a new Canvas.

2

Canvas(GraphicsConfiguration config)

Constructs a new Canvas given a GraphicsConfiguration object.

Canvas()

Constructs a new Canvas.

Canvas(GraphicsConfiguration config)

Constructs a new Canvas given a GraphicsConfiguration object.

Методы класса

SN Метод и описание
1

void addNotify()

Creates the peer of the canvas.

2

void createBufferStrategy(int numBuffers)

Creates a new strategy for multi-buffering on this component.

3

void createBufferStrategy(int numBuffers, BufferCapabilities caps)

Creates a new strategy for multi-buffering on this component with the required buffer capabilities.

4

AccessibleContext getAccessibleContext()

Gets the AccessibleContext associated with this Canvas.

5

BufferStrategy getBufferStrategy()

Returns the BufferStrategy used by this component.

6

void paint(Graphics g)

Paints this canvas.

7

void pdate(Graphics g)

Updates this canvas.

void addNotify()

Creates the peer of the canvas.

void createBufferStrategy(int numBuffers)

Creates a new strategy for multi-buffering on this component.

void createBufferStrategy(int numBuffers, BufferCapabilities caps)

Creates a new strategy for multi-buffering on this component with the required buffer capabilities.

AccessibleContext getAccessibleContext()

Gets the AccessibleContext associated with this Canvas.

BufferStrategy getBufferStrategy()

Returns the BufferStrategy used by this component.

void paint(Graphics g)

Paints this canvas.

void pdate(Graphics g)

Updates this canvas.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.awt.Component

  • java.lang.Object

java.awt.Component

java.lang.Object

Canvas Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtControlDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtControlDemo  awtControlDemo = new AwtControlDemo();
      awtControlDemo.showCanvasDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showCanvasDemo(){
      headerLabel.setText("Control in action: Canvas"); 

      controlPanel.add(new MyCanvas());
      mainFrame.setVisible(true);  
   } 

   class MyCanvas extends Canvas {

      public MyCanvas () {
         setBackground (Color.GRAY);
         setSize(300, 300);
      }

      public void paint (Graphics g) {
         Graphics2D g2;
         g2 = (Graphics2D) g;
         g2.drawString ("It is a custom canvas area", 70, 70);
      }
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Проверьте следующий вывод

AWT Canvas

AWT Image Class

Вступление

Image control is superclass for all image classes representing graphical images.

Объявление класса

Following is the declaration for java.awt.Image class:

public abstract class Image
   extends Object

поле

Following are the fields for java.awt.Image class:

  • protected float accelerationPriority — Priority for accelerating this image.

  • static int SCALE_AREA_AVERAGING — Use the Area Averaging image scaling algorithm.

  • static int SCALE_DEFAULT — Use the default image-scaling algorithm.

  • static int SCALE_FAST — Choose an image-scaling algorithm that gives higher priority to scaling speed than smoothness of the scaled image.

  • static int SCALE_REPLICATE — Use the image scaling algorithm embodied in the ReplicateScaleFilter class.

  • static int SCALE_SMOOTH — Choose an image-scaling algorithm that gives higher priority to image smoothness than scaling speed.

  • static Object UndefinedProperty — The UndefinedProperty object should be returned whenever a property which was not defined for a particular image is fetched.

protected float accelerationPriority — Priority for accelerating this image.

static int SCALE_AREA_AVERAGING — Use the Area Averaging image scaling algorithm.

static int SCALE_DEFAULT — Use the default image-scaling algorithm.

static int SCALE_FAST — Choose an image-scaling algorithm that gives higher priority to scaling speed than smoothness of the scaled image.

static int SCALE_REPLICATE — Use the image scaling algorithm embodied in the ReplicateScaleFilter class.

static int SCALE_SMOOTH — Choose an image-scaling algorithm that gives higher priority to image smoothness than scaling speed.

static Object UndefinedProperty — The UndefinedProperty object should be returned whenever a property which was not defined for a particular image is fetched.

Конструкторы классов

SN Конструктор и описание
1

Image()

Image()

Методы класса

SN Метод и описание
1

void flush()

Flushes all reconstructable resources being used by this Image object.

2

float getAccelerationPriority()

Returns the current value of the acceleration priority hint.

3

ImageCapabilities getCapabilities(GraphicsConfiguration gc)

Returns an ImageCapabilities object which can be inquired as to the capabilities of this Image on the specified GraphicsConfiguration.

4

abstract Graphics getGraphics()

Creates a graphics context for drawing to an off-screen image.

5

abstract int getHeight(ImageObserver observer)

Determines the height of the image.

6

abstract Object getProperty(String name, ImageObserver observer)

Gets a property of this image by name.

7

Image getScaledInstance(int width, int height, int hints)

Creates a scaled version of this image.

8

abstract ImageProducer getSource()

Gets the object that produces the pixels for the image.

9

abstract int getWidth(ImageObserver observer)

Determines the width of the image.

10

void setAccelerationPriority(float priority)

Sets a hint for this image about how important acceleration is.

void flush()

Flushes all reconstructable resources being used by this Image object.

float getAccelerationPriority()

Returns the current value of the acceleration priority hint.

ImageCapabilities getCapabilities(GraphicsConfiguration gc)

Returns an ImageCapabilities object which can be inquired as to the capabilities of this Image on the specified GraphicsConfiguration.

abstract Graphics getGraphics()

Creates a graphics context for drawing to an off-screen image.

abstract int getHeight(ImageObserver observer)

Determines the height of the image.

abstract Object getProperty(String name, ImageObserver observer)

Gets a property of this image by name.

Image getScaledInstance(int width, int height, int hints)

Creates a scaled version of this image.

abstract ImageProducer getSource()

Gets the object that produces the pixels for the image.

abstract int getWidth(ImageObserver observer)

Determines the width of the image.

void setAccelerationPriority(float priority)

Sets a hint for this image about how important acceleration is.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.lang.Object

java.lang.Object

Image Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtControlDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtControlDemo  awtControlDemo = new AwtControlDemo();
      awtControlDemo.showImageDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showImageDemo(){
      headerLabel.setText("Control in action: Image"); 

      controlPanel.add(new ImageComponent("resources/java.jpg"));
      mainFrame.setVisible(true);  
   }
	
   class ImageComponent extends Component {

      BufferedImage img;

      public void paint(Graphics g) {
         g.drawImage(img, 0, 0, null);
      }

      public ImageComponent(String path) {
         try {
            img = ImageIO.read(new File(path));
         } catch (IOException e) {
            e.printStackTrace();
         }
      }

      public Dimension getPreferredSize() {
         if (img == null) {
            return new Dimension(100,100);
         } else {
            return new Dimension(img.getWidth(), img.getHeight());
         }
      }
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Проверьте следующий вывод

AWT Image

AWT Scrollbar Class

Вступление

Scrollbar control represents a scroll bar component in order to enable user to select from range of values.

Объявление класса

Following is the declaration for java.awt.Scrollbar class:

public class Scrollbar
   extends Component
      implements Adjustable, Accessible

поле

Following are the fields for java.awt.Image class:

  • static int HORIZONTAL –A constant that indicates a horizontal scroll bar.

  • static int VERTICAL –A constant that indicates a vertical scroll bar.

static int HORIZONTAL –A constant that indicates a horizontal scroll bar.

static int VERTICAL –A constant that indicates a vertical scroll bar.

Конструкторы классов

SN Конструктор и описание
1

Scrollbar()

Constructs a new vertical scroll bar.

2

Scrollbar(int orientation)

Constructs a new scroll bar with the specified orientation.

3

Scrollbar(int orientation, int value, int visible, int minimum, int maximum)

Constructs a new scroll bar with the specified orientation, initial value, visible amount, and minimum and maximum values.

Scrollbar()

Constructs a new vertical scroll bar.

Scrollbar(int orientation)

Constructs a new scroll bar with the specified orientation.

Scrollbar(int orientation, int value, int visible, int minimum, int maximum)

Constructs a new scroll bar with the specified orientation, initial value, visible amount, and minimum and maximum values.

Методы класса

AccessibleContext getAccessibleContext()

Gets the AccessibleContext associated with this Scrollbar.

AdjustmentListener[] getAdjustmentListeners()

Returns an array of all the adjustment listeners registered on this scrollbar.

<T extends EventListener>T[] getListeners(Class<T> listenerType)

Returns an array of all the objects currently registered as FooListeners upon this Scrollbar.

SN Метод и описание
1

void addAdjustmentListener(AdjustmentListener l)

Adds the specified adjustment listener to receive instances of AdjustmentEvent from this scroll bar.

2

void addNotify()

Creates the Scrollbar’s peer.

3

int getBlockIncrement()

Gets the block increment of this scroll bar.

4

int getLineIncrement()

Устаревшее. As of JDK version 1.1, replaced by getUnitIncrement().

5

int getMaximum()

Gets the maximum value of this scroll bar.

6

int getMinimum()

Gets the minimum value of this scroll bar.

7

int getOrientation()

Returns the orientation of this scroll bar.

8

int getPageIncrement()

Устаревшее. As of JDK version 1.1, replaced by getBlockIncrement().

9

int getUnitIncrement()

Gets the unit increment for this scrollbar.

10

int getValue()

Gets the current value of this scroll bar.

11

логический

getValueIsAdjusting()

Returns true if the value is in the process of changing as a result of actions being taken by the user.

12

int getVisible()

Устаревшее. As of JDK version 1.1, replaced by getVisibleAmount().

13

int getVisibleAmount()

Gets the visible amount of this scroll bar.

14

protected String paramString()

Returns a string representing the state of this Scrollbar.

15

protected void processAdjustmentEvent(AdjustmentEvent e)

Processes adjustment events occurring on this scrollbar by dispatching them to any registered AdjustmentListener objects.

16

защищенный

1

void processEvent(AWTEvent e)

Processes events on this scroll bar.

17

void removeAdjustmentListener(AdjustmentListener l)

Removes the specified adjustment listener so that it no longer receives instances of AdjustmentEvent from this scroll bar.

18

void setBlockIncrement(int v)

Sets the block increment for this scroll bar.

19

void setLineIncrement(int v)

Устаревшее. As of JDK version 1.1, replaced by setUnitIncrement(int).

20

void setMaximum(int newMaximum)

Sets the maximum value of this scroll bar.

21

void setMinimum(int newMinimum)

Sets the minimum value of this scroll bar.

22

void setOrientation(int orientation)

Sets the orientation for this scroll bar.

23

void setPageIncrement(int v)

Устаревшее. As of JDK version 1.1, replaced by setBlockIncrement().

24

void setUnitIncrement(int v)

Sets the unit increment for this scroll bar.

25

void setValue(int newValue)

Sets the value of this scroll bar to the specified value.

26

void setValueIsAdjusting(boolean b)

Sets the valueIsAdjusting property.

27

void setValues(int value, int visible, int minimum, int maximum)

Sets the values of four properties for this scroll bar: value, visibleAmount, minimum, and maximum.

28

void setVisibleAmount(int newAmount)

Sets the visible amount of this scroll bar.

void addAdjustmentListener(AdjustmentListener l)

Adds the specified adjustment listener to receive instances of AdjustmentEvent from this scroll bar.

void addNotify()

Creates the Scrollbar’s peer.

int getBlockIncrement()

Gets the block increment of this scroll bar.

int getLineIncrement()

Устаревшее. As of JDK version 1.1, replaced by getUnitIncrement().

int getMaximum()

Gets the maximum value of this scroll bar.

int getMinimum()

Gets the minimum value of this scroll bar.

int getOrientation()

Returns the orientation of this scroll bar.

int getPageIncrement()

Устаревшее. As of JDK version 1.1, replaced by getBlockIncrement().

int getUnitIncrement()

Gets the unit increment for this scrollbar.

int getValue()

Gets the current value of this scroll bar.

логический

getValueIsAdjusting()

Returns true if the value is in the process of changing as a result of actions being taken by the user.

int getVisible()

Устаревшее. As of JDK version 1.1, replaced by getVisibleAmount().

int getVisibleAmount()

Gets the visible amount of this scroll bar.

protected String paramString()

Returns a string representing the state of this Scrollbar.

protected void processAdjustmentEvent(AdjustmentEvent e)

Processes adjustment events occurring on this scrollbar by dispatching them to any registered AdjustmentListener objects.

защищенный

void processEvent(AWTEvent e)

Processes events on this scroll bar.

void removeAdjustmentListener(AdjustmentListener l)

Removes the specified adjustment listener so that it no longer receives instances of AdjustmentEvent from this scroll bar.

void setBlockIncrement(int v)

Sets the block increment for this scroll bar.

void setLineIncrement(int v)

Устаревшее. As of JDK version 1.1, replaced by setUnitIncrement(int).

void setMaximum(int newMaximum)

Sets the maximum value of this scroll bar.

void setMinimum(int newMinimum)

Sets the minimum value of this scroll bar.

void setOrientation(int orientation)

Sets the orientation for this scroll bar.

void setPageIncrement(int v)

Устаревшее. As of JDK version 1.1, replaced by setBlockIncrement().

void setUnitIncrement(int v)

Sets the unit increment for this scroll bar.

void setValue(int newValue)

Sets the value of this scroll bar to the specified value.

void setValueIsAdjusting(boolean b)

Sets the valueIsAdjusting property.

void setValues(int value, int visible, int minimum, int maximum)

Sets the values of four properties for this scroll bar: value, visibleAmount, minimum, and maximum.

void setVisibleAmount(int newAmount)

Sets the visible amount of this scroll bar.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.awt.Component

  • java.lang.Object

java.awt.Component

java.lang.Object

Scrollbar Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtControlDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtControlDemo  awtControlDemo = new AwtControlDemo();
      awtControlDemo.showScrollbarDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showScrollbarDemo(){                                       
      headerLabel.setText("Control in action: Scrollbar"); 

      final Scrollbar horizontalScroller = new Scrollbar(Scrollbar.HORIZONTAL);
      final Scrollbar verticalScroller = new Scrollbar();
      verticalScroller.setOrientation(Scrollbar.VERTICAL);
      horizontalScroller.setMaximum (100);
      horizontalScroller.setMinimum (1);
      verticalScroller.setMaximum (100);
      verticalScroller.setMinimum (1);

      horizontalScroller.addAdjustmentListener(new AdjustmentListener() {

         @Override
         public void adjustmentValueChanged(AdjustmentEvent e) {
            statusLabel.setText("Horozontal: "
               +horizontalScroller.getValue() 
               +" ,Vertical: "
               + verticalScroller.getValue());
            }
         });

      verticalScroller.addAdjustmentListener(new AdjustmentListener() {

            @Override
            public void adjustmentValueChanged(AdjustmentEvent e) {
               statusLabel.setText("Horozontal: "
               +horizontalScroller.getValue() 
               +" ,Vertical: "+ verticalScroller.getValue());
            }
         });

      controlPanel.add(horizontalScroller);
      controlPanel.add(verticalScroller);

      mainFrame.setVisible(true);  
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Проверьте следующий вывод

AWT Scrollbar

AWT Dialog Class

Вступление

Dialog control represents a top-level window with a title and a border used to take some form of input from the user.

Объявление класса

Following is the declaration for java.awt.Dialog class:

public class Dialog
extends Window

поле

Following are the fields for java.awt.Image class:

  • static Dialog.ModalityType DEFAULT_MODALITY_TYPE — Default modality type for modal dialogs.

static Dialog.ModalityType DEFAULT_MODALITY_TYPE — Default modality type for modal dialogs.

Конструкторы классов

SN Конструктор и описание
1

Dialog(Dialog owner)

Constructs an initially invisible, modeless Dialog with the specified owner Dialog and an empty title.

2

Dialog(Dialog owner, String title)

Constructs an initially invisible, modeless Dialog with the specified owner Dialog and title.

3

Dialog(Dialog owner, String title, boolean modal)

Constructs an initially invisible Dialog with the specified owner Dialog, title, and modality.

4

Dialog(Dialog owner, String title, boolean modal, GraphicsConfiguration gc)

Constructs an initially invisible Dialog with the specified owner Dialog, title, modality and GraphicsConfiguration.

5

Dialog(Frame owner)

Constructs an initially invisible, modeless Dialog with the specified owner Frame and an empty title.

6

Dialog(Frame owner, boolean modal)

Constructs an initially invisible Dialog with the specified owner Frame and modality and an empty title.

7

Dialog(Frame owner, String title)

Constructs an initially invisible, modeless Dialog with the specified owner Frame and title.

8

Dialog(Frame owner, String title, boolean modal)

Constructs an initially invisible Dialog with the specified owner Frame, title and modality.

9

Dialog(Frame owner, String title, boolean modal, GraphicsConfiguration gc)

Constructs an initially invisible Dialog with the specified owner Frame, title, modality, and GraphicsConfiguration.

10

Dialog(Window owner)

Constructs an initially invisible, modeless Dialog with the specified owner Window and an empty title.

11

Dialog(Window owner, Dialog.ModalityType modalityType)

Constructs an initially invisible Dialog with the specified owner Window and modality and an empty title.

12

Dialog(Window owner, String title)

Constructs an initially invisible, modeless Dialog with the specified owner Window and title.

13

Dialog(Window owner, String title, Dialog.ModalityType modalityType)

Constructs an initially invisible Dialog with the specified owner Window, title and modality.

14

Dialog(Window owner, String title, Dialog.ModalityType modalityType, GraphicsConfiguration gc)

Constructs an initially invisible Dialog with the specified owner Window, title, modality and GraphicsConfiguration

Dialog(Dialog owner)

Constructs an initially invisible, modeless Dialog with the specified owner Dialog and an empty title.

Dialog(Dialog owner, String title)

Constructs an initially invisible, modeless Dialog with the specified owner Dialog and title.

Dialog(Dialog owner, String title, boolean modal)

Constructs an initially invisible Dialog with the specified owner Dialog, title, and modality.

Dialog(Dialog owner, String title, boolean modal, GraphicsConfiguration gc)

Constructs an initially invisible Dialog with the specified owner Dialog, title, modality and GraphicsConfiguration.

Dialog(Frame owner)

Constructs an initially invisible, modeless Dialog with the specified owner Frame and an empty title.

Dialog(Frame owner, boolean modal)

Constructs an initially invisible Dialog with the specified owner Frame and modality and an empty title.

Dialog(Frame owner, String title)

Constructs an initially invisible, modeless Dialog with the specified owner Frame and title.

Dialog(Frame owner, String title, boolean modal)

Constructs an initially invisible Dialog with the specified owner Frame, title and modality.

Dialog(Frame owner, String title, boolean modal, GraphicsConfiguration gc)

Constructs an initially invisible Dialog with the specified owner Frame, title, modality, and GraphicsConfiguration.

Dialog(Window owner)

Constructs an initially invisible, modeless Dialog with the specified owner Window and an empty title.

Dialog(Window owner, Dialog.ModalityType modalityType)

Constructs an initially invisible Dialog with the specified owner Window and modality and an empty title.

Dialog(Window owner, String title)

Constructs an initially invisible, modeless Dialog with the specified owner Window and title.

Dialog(Window owner, String title, Dialog.ModalityType modalityType)

Constructs an initially invisible Dialog with the specified owner Window, title and modality.

Dialog(Window owner, String title, Dialog.ModalityType modalityType, GraphicsConfiguration gc)

Constructs an initially invisible Dialog with the specified owner Window, title, modality and GraphicsConfiguration

Методы класса

SN Метод и описание
1

void addNotify()

Makes this Dialog displayable by connecting it to a native screen resource.

2

AccessibleContext getAccessibleContext()

Gets the AccessibleContext associated with this Dialog.

3

Dialog.ModalityType getModalityType()

Returns the modality type of this dialog.

4

String getTitle()

Gets the title of the dialog.

5

void hide()

Устаревшее. As of JDK version 1.5, replaced by setVisible(boolean).

6

boolean isModal()

Indicates whether the dialog is modal.

7

boolean isResizable()

Indicates whether this dialog is resizable by the user.

8

boolean isUndecorated()

Indicates whether this dialog is undecorated.

9

protected String paramString()

Returns a string representing the state of this dialog.

10

void setModal(boolean modal)

Specifies whether this dialog should be modal.

11

void setModalityType(Dialog.ModalityType type)

Sets the modality type for this dialog.

12

void setResizable(boolean resizable)

Sets whether this dialog is resizable by the user.

13

void setTitle(String title)

Sets the title of the Dialog.

14

void setUndecorated(boolean undecorated)

Disables or enables decorations for this dialog.

15

void setVisible(boolean b)

Shows or hides this Dialog depending on the value of parameter b.

16

void show()

Устаревшее. As of JDK version 1.5, replaced by setVisible(boolean).

17

void toBack()

If this Window is visible, sends this Window to the back and may cause it to lose focus or activation if it is the focused or active Window.

void addNotify()

Makes this Dialog displayable by connecting it to a native screen resource.

AccessibleContext getAccessibleContext()

Gets the AccessibleContext associated with this Dialog.

Dialog.ModalityType getModalityType()

Returns the modality type of this dialog.

String getTitle()

Gets the title of the dialog.

void hide()

Устаревшее. As of JDK version 1.5, replaced by setVisible(boolean).

boolean isModal()

Indicates whether the dialog is modal.

boolean isResizable()

Indicates whether this dialog is resizable by the user.

boolean isUndecorated()

Indicates whether this dialog is undecorated.

protected String paramString()

Returns a string representing the state of this dialog.

void setModal(boolean modal)

Specifies whether this dialog should be modal.

void setModalityType(Dialog.ModalityType type)

Sets the modality type for this dialog.

void setResizable(boolean resizable)

Sets whether this dialog is resizable by the user.

void setTitle(String title)

Sets the title of the Dialog.

void setUndecorated(boolean undecorated)

Disables or enables decorations for this dialog.

void setVisible(boolean b)

Shows or hides this Dialog depending on the value of parameter b.

void show()

Устаревшее. As of JDK version 1.5, replaced by setVisible(boolean).

void toBack()

If this Window is visible, sends this Window to the back and may cause it to lose focus or activation if it is the focused or active Window.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.awt.Window

  • java.awt.Component

  • java.lang.Object

java.awt.Window

java.awt.Component

java.lang.Object

Dialog Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtControlDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtControlDemo  awtControlDemo = new AwtControlDemo();
      awtControlDemo.showDialogDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showDialogDemo(){
      headerLabel.setText("Control in action: Dialog"); 
      Button showAboutDialogButton = new Button("Show About Dialog");
      showAboutDialogButton.addActionListener(new ActionListener() {
	     @Override
         public void actionPerformed(ActionEvent e) {
            AboutDialog aboutDialog = new AboutDialog(mainFrame);
            aboutDialog.setVisible(true);
         }
      });

      controlPanel.add(showAboutDialogButton);
      mainFrame.setVisible(true);  
   }

   class AboutDialog extends Dialog {
      public AboutDialog(Frame parent){
         super(parent, true);         
         setBackground(Color.gray);
         setLayout(new BorderLayout());
         Panel panel = new Panel();
         panel.add(new Button("Close"));
         add("South", panel);
         setSize(200,200);

         addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent windowEvent){
               dispose();
            }
         });
      }

      public boolean action(Event evt, Object arg){
         if(arg.equals("Close")){
            dispose();
            return true;
         }
         return false;
      }

      public void paint(Graphics g){
         g.setColor(Color.white);
         g.drawString("TutorialsPoint.Com", 25,70 );
         g.drawString("Version 1.0", 60, 90);      
      }
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Проверьте следующий вывод

AWT Dialog

AWT FileDialog Class

Вступление

FileDialog control represents a dialog window from which the user can select a file.

Объявление класса

Following is the declaration for java.awt.FileDialog class:

public class FileDialog
   extends Dialog

поле

Following are the fields for java.awt.Image class:

  • static int LOAD — This constant value indicates that the purpose of the file dialog window is to locate a file from which to read.

  • static int SAVE — This constant value indicates that the purpose of the file dialog window is to locate a file to which to write.

static int LOAD — This constant value indicates that the purpose of the file dialog window is to locate a file from which to read.

static int SAVE — This constant value indicates that the purpose of the file dialog window is to locate a file to which to write.

Конструкторы классов

SN Конструктор и описание
1

FileDialog(Dialog parent)

Creates a file dialog for loading a file.

2

FileDialog(Dialog parent, String title)

Creates a file dialog window with the specified title for loading a file.

3

FileDialog(Dialog parent, String title, int mode)

Creates a file dialog window with the specified title for loading or saving a file.

4

FileDialog(Frame parent)

Creates a file dialog for loading a file.

5

FileDialog(Frame parent, String title)

Creates a file dialog window with the specified title for loading a file.

6

FileDialog(Frame parent, String title, int mode)

Creates a file dialog window with the specified title for loading or saving a file.

FileDialog(Dialog parent)

Creates a file dialog for loading a file.

FileDialog(Dialog parent, String title)

Creates a file dialog window with the specified title for loading a file.

FileDialog(Dialog parent, String title, int mode)

Creates a file dialog window with the specified title for loading or saving a file.

FileDialog(Frame parent)

Creates a file dialog for loading a file.

FileDialog(Frame parent, String title)

Creates a file dialog window with the specified title for loading a file.

FileDialog(Frame parent, String title, int mode)

Creates a file dialog window with the specified title for loading or saving a file.

Методы класса

SN Метод и описание
1

void addNotify()

Creates the file dialog’s peer.

2

String getDirectory()

Gets the directory of this file dialog.

3

String getFile()

Gets the selected file of this file dialog.

4

FilenameFilter getFilenameFilter()

Determines this file dialog’s filename filter.

5

int getMode()

Indicates whether this file dialog box is for loading from a file or for saving to a file.

6

protected String paramString()

Returns a string representing the state of this FileDialog window.

7

void setDirectory(String dir)

Sets the directory of this file dialog window to be the specified directory.

8

void setFile(String file)

Sets the selected file for this file dialog window to be the specified file.

9

void setFilenameFilter(FilenameFilter filter)

Sets the filename filter for this file dialog window to the specified filter.

10

void setMode(int mode)

Sets the mode of the file dialog.

void addNotify()

Creates the file dialog’s peer.

String getDirectory()

Gets the directory of this file dialog.

String getFile()

Gets the selected file of this file dialog.

FilenameFilter getFilenameFilter()

Determines this file dialog’s filename filter.

int getMode()

Indicates whether this file dialog box is for loading from a file or for saving to a file.

protected String paramString()

Returns a string representing the state of this FileDialog window.

void setDirectory(String dir)

Sets the directory of this file dialog window to be the specified directory.

void setFile(String file)

Sets the selected file for this file dialog window to be the specified file.

void setFilenameFilter(FilenameFilter filter)

Sets the filename filter for this file dialog window to the specified filter.

void setMode(int mode)

Sets the mode of the file dialog.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.awt.Dialog

  • java.awt.Window

  • java.awt.Component

  • java.lang.Object

java.awt.Dialog

java.awt.Window

java.awt.Component

java.lang.Object

FileDialog Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtControlDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtControlDemo  awtControlDemo = new AwtControlDemo();
      awtControlDemo.showFileDialogDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showFileDialogDemo(){
      headerLabel.setText("Control in action: FileDialog"); 

      final FileDialog fileDialog = new FileDialog(mainFrame,"Select file");
      Button showFileDialogButton = new Button("Open File");
      showFileDialogButton.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            fileDialog.setVisible(true);
            statusLabel.setText("File Selected :" 
            + fileDialog.getDirectory() + fileDialog.getFile());
         }
      });

      controlPanel.add(showFileDialogButton);
      mainFrame.setVisible(true);  
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Проверьте следующий вывод

AWT FileDialog

Обработка событий

Что такое событие?

Изменение состояния объекта называется событием, т.е. событие описывает изменение состояния источника. События генерируются в результате взаимодействия пользователя с компонентами графического интерфейса пользователя. Например, нажатие кнопки, перемещение мыши, ввод символа с клавиатуры, выбор элемента из списка, прокрутка страницы – действия, которые вызывают событие.

Типы событий

События могут быть в целом классифицированы на две категории:

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

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

События на переднем плане – те события, которые требуют непосредственного взаимодействия с пользователем. Они генерируются как последствия взаимодействия человека с графическими компонентами в графическом интерфейсе пользователя. Например, нажатие кнопки, перемещение мыши, ввод символа с клавиатуры, выбор элемента из списка, прокрутка страницы и т. Д.

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

Что такое обработка событий?

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

Модель делегирования событий включает в себя следующих ключевых участников, а именно:

  • Источник – Источник – это объект, на котором происходит событие. Источник отвечает за предоставление информации о произошедшем событии своему обработчику. Java предоставляют как с классами для исходного объекта.

  • Слушатель. Он также известен как обработчик события. Слушатель отвечает за генерацию ответа на событие. С точки зрения реализации Java слушатель также является объектом. Слушатель ждет, пока не получит событие. Как только событие получено, слушатель обрабатывает событие и затем возвращается.

Источник – Источник – это объект, на котором происходит событие. Источник отвечает за предоставление информации о произошедшем событии своему обработчику. Java предоставляют как с классами для исходного объекта.

Слушатель. Он также известен как обработчик события. Слушатель отвечает за генерацию ответа на событие. С точки зрения реализации Java слушатель также является объектом. Слушатель ждет, пока не получит событие. Как только событие получено, слушатель обрабатывает событие и затем возвращается.

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

Шаги, связанные с обработкой событий

  • Пользователь нажимает кнопку, и событие генерируется.

  • Теперь объект соответствующего класса событий создается автоматически, и информация об источнике и событии заполняется одним и тем же объектом.

  • Объект события перенаправляется в метод зарегистрированного класса слушателя.

  • метод теперь выполняется и возвращается.

Пользователь нажимает кнопку, и событие генерируется.

Теперь объект соответствующего класса событий создается автоматически, и информация об источнике и событии заполняется одним и тем же объектом.

Объект события перенаправляется в метод зарегистрированного класса слушателя.

метод теперь выполняется и возвращается.

Что нужно помнить о слушателе

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

  • Если вы не реализуете предопределенные интерфейсы any if, тогда ваш класс не может выступать в качестве класса слушателя для исходного объекта.

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

Если вы не реализуете предопределенные интерфейсы any if, тогда ваш класс не может выступать в качестве класса слушателя для исходного объекта.

Методы обратного вызова

Это методы, предоставляемые провайдером API и определяемые программистом приложения и вызываемые разработчиком приложения. Здесь методы обратного вызова представляют метод события. В ответ на событие java jre запустит метод обратного вызова. Все такие методы обратного вызова предоставляются в интерфейсах слушателей.

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

Пример обработки событий

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtControlDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtControlDemo  awtControlDemo = new AwtControlDemo();
      awtControlDemo.showEventDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showEventDemo(){
      headerLabel.setText("Control in action: Button"); 

      Button okButton = new Button("OK");
      Button submitButton = new Button("Submit");
      Button cancelButton = new Button("Cancel");

      okButton.setActionCommand("OK");
      submitButton.setActionCommand("Submit");
      cancelButton.setActionCommand("Cancel");

      okButton.addActionListener(new ButtonClickListener()); 
      submitButton.addActionListener(new ButtonClickListener()); 
      cancelButton.addActionListener(new ButtonClickListener()); 

      controlPanel.add(okButton);
      controlPanel.add(submitButton);
      controlPanel.add(cancelButton);       

      mainFrame.setVisible(true);  
   }

   private class ButtonClickListener implements ActionListener{
      public void actionPerformed(ActionEvent e) {
         String command = e.getActionCommand();  
         if( command.equals( "OK" ))  {
            statusLabel.setText("Ok Button clicked.");
         }
         else if( command.equals( "Submit" ) )  {
            statusLabel.setText("Submit Button clicked."); 
         }
         else  {
            statusLabel.setText("Cancel Button clicked.");
         }  	
      }		
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Проверьте следующий вывод

Обработка событий AWT

Классы событий AWT

Классы Event представляют событие. Java предоставляет нам различные классы Event, но мы обсудим те, которые используются чаще.

Класс EventObject

Это корневой класс, из которого должны быть получены все объекты состояния события. Все события построены со ссылкой на объект, источник , который логически считается объектом, с которым первоначально произошло рассматриваемое событие. This class is defined in java.util package.

Объявление класса

Ниже приводится объявление для класса java.util.EventObject :

public class EventObject
   extends Object
      implements Serializable

поле

Ниже приведены поля для класса java.util.EventObject :

  • Защищенный источник объекта – объект, на котором изначально произошло событие.

Защищенный источник объекта – объект, на котором изначально произошло событие.

Конструкторы классов

SN Конструктор и описание
1

EventObject (Источник объекта)

Создает прототип события.

EventObject (Источник объекта)

Создает прототип события.

Методы класса

SN Метод и описание
1

Объект getSource ()

Объект, на котором изначально произошло Событие.

2

Строка toString ()

Возвращает строковое представление этого EventObject.

Объект getSource ()

Объект, на котором изначально произошло Событие.

Строка toString ()

Возвращает строковое представление этого EventObject.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.lang.Object

java.lang.Object

Классы событий AWT:

Ниже приведен список наиболее часто используемых классов событий.

AWT AWTEvent Class

Это корневой класс событий для всех событий AWT. Этот класс и его подклассы заменяют исходный класс java.awt.Event. This class is defined in java.awt package. This class has a method named getID() that can be used to determine the type of event.

Объявление класса

Following is the declaration for java.awt.AWTEvent class:

public class AWTEvent
   extends EventObject

поле

Following are the fields for java.awt.AWTEvent class:

  • static int ACTION_FIRST — The first number in the range of ids used for action events.

  • static long ACTION_EVENT_MASK — The event mask for selecting action events.

  • static long ADJUSTMENT_EVENT_MASK — The event mask for selecting adjustment events.

  • static long COMPONENT_EVENT_MASK — The event mask for selecting component events.

  • protected boolean consumed — Controls whether or not the event is sent back down to the peer once the source has processed it – false means it’s sent to the peer; true means it’s not.

  • static long CONTAINER_EVENT_MASK — The event mask for selecting container events.

  • static long FOCUS_EVENT_MASK — The event mask for selecting focus events.

  • static long HIERARCHY_BOUNDS_EVENT_MASK — The event mask for selecting hierarchy bounds events.

  • static long HIERARCHY_EVENT_MASK — The event mask for selecting hierarchy events.

  • protected int id — The event’s id.

  • static long INPUT_METHOD_EVENT_MASK — The event mask for selecting input method events.

  • static long INVOCATION_EVENT_MASK — The event mask for selecting invocation events.

  • static long ITEM_EVENT_MASK — The event mask for selecting item events.

  • static long KEY_EVENT_MASK — The event mask for selecting key events.

  • static long MOUSE_EVENT_MASK — The event mask for selecting mouse events.

  • static long MOUSE_MOTION_EVENT_MASK — The event mask for selecting mouse motion events.

  • static long MOUSE_WHEEL_EVENT_MASK — The event mask for selecting mouse wheel events.

  • static long PAINT_EVENT_MASK — The event mask for selecting paint events.

  • static int RESERVED_ID_MAX — The maximum value for reserved AWT event IDs.

  • static long TEXT_EVENT_MASK — The event mask for selecting text events.

  • static long WINDOW_EVENT_MASK — The event mask for selecting window events.

  • static long WINDOW_FOCUS_EVENT_MASK — The event mask for selecting window focus events.

  • static long WINDOW_STATE_EVENT_MASK — The event mask for selecting window state events.

static int ACTION_FIRST — The first number in the range of ids used for action events.

static long ACTION_EVENT_MASK — The event mask for selecting action events.

static long ADJUSTMENT_EVENT_MASK — The event mask for selecting adjustment events.

static long COMPONENT_EVENT_MASK — The event mask for selecting component events.

protected boolean consumed — Controls whether or not the event is sent back down to the peer once the source has processed it – false means it’s sent to the peer; true means it’s not.

static long CONTAINER_EVENT_MASK — The event mask for selecting container events.

static long FOCUS_EVENT_MASK — The event mask for selecting focus events.

static long HIERARCHY_BOUNDS_EVENT_MASK — The event mask for selecting hierarchy bounds events.

static long HIERARCHY_EVENT_MASK — The event mask for selecting hierarchy events.

protected int id — The event’s id.

static long INPUT_METHOD_EVENT_MASK — The event mask for selecting input method events.

static long INVOCATION_EVENT_MASK — The event mask for selecting invocation events.

static long ITEM_EVENT_MASK — The event mask for selecting item events.

static long KEY_EVENT_MASK — The event mask for selecting key events.

static long MOUSE_EVENT_MASK — The event mask for selecting mouse events.

static long MOUSE_MOTION_EVENT_MASK — The event mask for selecting mouse motion events.

static long MOUSE_WHEEL_EVENT_MASK — The event mask for selecting mouse wheel events.

static long PAINT_EVENT_MASK — The event mask for selecting paint events.

static int RESERVED_ID_MAX — The maximum value for reserved AWT event IDs.

static long TEXT_EVENT_MASK — The event mask for selecting text events.

static long WINDOW_EVENT_MASK — The event mask for selecting window events.

static long WINDOW_FOCUS_EVENT_MASK — The event mask for selecting window focus events.

static long WINDOW_STATE_EVENT_MASK — The event mask for selecting window state events.

Конструкторы классов

SN Конструктор и описание
1

AWTEvent(Event event)

Constructs an AWTEvent object from the parameters of a 1.0-style event.

2

AWTEvent(java.lang.Object source, int id)

Constructs an AWTEvent object with the specified source object and type.

AWTEvent(Event event)

Constructs an AWTEvent object from the parameters of a 1.0-style event.

AWTEvent(java.lang.Object source, int id)

Constructs an AWTEvent object with the specified source object and type.

Методы класса

SN Метод и описание
1

protected void consume()

Consumes this event, if this event can be consumed.

2

int getID()

Returns the event type.

3

protected boolean isConsumed()

Returns whether this event has been consumed.

4

java.lang.String paramString()

Returns a string representing the state of this Event.

5

void setSource(java.lang.Object newSource)

Retargets an event to a new source.

6

java.lang.String toString()

Returns a String representation of this object.

protected void consume()

Consumes this event, if this event can be consumed.

int getID()

Returns the event type.

protected boolean isConsumed()

Returns whether this event has been consumed.

java.lang.String paramString()

Returns a string representing the state of this Event.

void setSource(java.lang.Object newSource)

Retargets an event to a new source.

java.lang.String toString()

Returns a String representation of this object.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.util.EventObject

  • java.lang.Object

java.util.EventObject

java.lang.Object

AWT ActionEvent Class

This class is defined in java.awt.event package. Событие ActionEvent генерируется при нажатии кнопки или двойном щелчке элемента списка.

Объявление класса

Following is the declaration for java.awt.event.ActionEvent class:

public class ActionEvent
   extends AWTEvent

поле

Following are the fields for java.awt.event.ActionEvent class:

  • static int ACTION_FIRST — The first number in the range of ids used for action events.

  • static int ACTION_LAST — The last number in the range of ids used for action events.

  • static int ACTION_PERFORMED — This event id indicates that a meaningful action occured.

  • static int ALT_MASK — The alt modifier.

  • static int CTRL_MASK — The control modifier.

  • static int META_MASK — The meta modifier.

  • static int SHIFT_MASK — The shift modifier.

static int ACTION_FIRST — The first number in the range of ids used for action events.

static int ACTION_LAST — The last number in the range of ids used for action events.

static int ACTION_PERFORMED — This event id indicates that a meaningful action occured.

static int ALT_MASK — The alt modifier.

static int CTRL_MASK — The control modifier.

static int META_MASK — The meta modifier.

static int SHIFT_MASK — The shift modifier.

Конструкторы классов

SN Конструктор и описание
1

ActionEvent(java.lang.Object source, int id, java.lang.String command)

Constructs an ActionEvent object.

2

ActionEvent(java.lang.Object source, int id, java.lang.String command, int modifiers)

Constructs an ActionEvent object with modifier keys.

3

ActionEvent(java.lang.Object source, int id, java.lang.String command, long when, int modifiers)

Constructs an ActionEvent object with the specified modifier keys and timestamp.

ActionEvent(java.lang.Object source, int id, java.lang.String command)

Constructs an ActionEvent object.

ActionEvent(java.lang.Object source, int id, java.lang.String command, int modifiers)

Constructs an ActionEvent object with modifier keys.

ActionEvent(java.lang.Object source, int id, java.lang.String command, long when, int modifiers)

Constructs an ActionEvent object with the specified modifier keys and timestamp.

Методы класса

SN Метод и описание
1

java.lang.String getActionCommand()

Returns the command string associated with this action.

2

int getModifiers()

Returns the modifier keys held down during this action event.

3

long getWhen()

Returns the timestamp of when this event occurred.

4

java.lang.String paramString()

Returns a parameter string identifying this action event.

java.lang.String getActionCommand()

Returns the command string associated with this action.

int getModifiers()

Returns the modifier keys held down during this action event.

long getWhen()

Returns the timestamp of when this event occurred.

java.lang.String paramString()

Returns a parameter string identifying this action event.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.awt.AWTEvent

  • java.util.EventObject

  • java.lang.Object

java.awt.AWTEvent

java.util.EventObject

java.lang.Object

AWT InputEvent Class

Класс InputEvent является корневым классом событий для всех входных событий уровня компонента. Input events are delivered to listeners before they are processed normally by the source where they originated. This allows listeners and component subclasses to “consume” the event so that the source will not process them in their default manner. For example, consuming mousePressed events on a Button component will prevent the Button from being activated.

Объявление класса

Following is the declaration for java.awt.event.InputEvent class:

public abstract class InputEvent
   extends ComponentEvent

поле

Following are the fields for java.awt.event.InputEvent class:

  • static int ALT_DOWN_MASK — The Alt key extended modifier constant.

  • static int ALT_GRAPH_DOWN_MASK — The AltGraph key extended modifier constant.

  • static int ALT_GRAPH_MASK — The AltGraph key modifier constant.

  • static int ALT_MASK — The Alt key modifier constant.

  • static int BUTTON1_DOWN_MASK — The Mouse Button1 extended modifier constant.

  • static int BUTTON1_MASK — The Mouse Button1 modifier constant.

  • static int BUTTON2_DOWN_MASK — The Mouse Button2 extended modifier constant.

  • static int BUTTON2_MASK — The Mouse Button2 modifier constant.

  • static int BUTTON3_DOWN_MASK — The Mouse Button3 extended modifier constant.

  • static int BUTTON3_MASK –The Mouse Button3 modifier constant.

  • static int CTRL_DOWN_MASK — The Control key extended modifier constant.

  • static int CTRL_MASK — The Control key modifier constant.

  • static int META_DOWN_MASK — The Meta key extended modifier constant.

  • static int META_MASK — The Meta key modifier constant.

  • static int SHIFT_DOWN_MASK — The Shift key extended modifier constant.

  • static int SHIFT_MASK — The Shift key modifier constant.

static int ALT_DOWN_MASK — The Alt key extended modifier constant.

static int ALT_GRAPH_DOWN_MASK — The AltGraph key extended modifier constant.

static int ALT_GRAPH_MASK — The AltGraph key modifier constant.

static int ALT_MASK — The Alt key modifier constant.

static int BUTTON1_DOWN_MASK — The Mouse Button1 extended modifier constant.

static int BUTTON1_MASK — The Mouse Button1 modifier constant.

static int BUTTON2_DOWN_MASK — The Mouse Button2 extended modifier constant.

static int BUTTON2_MASK — The Mouse Button2 modifier constant.

static int BUTTON3_DOWN_MASK — The Mouse Button3 extended modifier constant.

static int BUTTON3_MASK –The Mouse Button3 modifier constant.

static int CTRL_DOWN_MASK — The Control key extended modifier constant.

static int CTRL_MASK — The Control key modifier constant.

static int META_DOWN_MASK — The Meta key extended modifier constant.

static int META_MASK — The Meta key modifier constant.

static int SHIFT_DOWN_MASK — The Shift key extended modifier constant.

static int SHIFT_MASK — The Shift key modifier constant.

Методы класса

S.N. Method & Description
1

void consume()

Consumes this event so that it will not be processed in the default manner by the source which originated it.

2

int getModifiers()

Returns the modifier mask for this event.

3

int getModifiersEx()

Returns the extended modifier mask for this event.

4

static String getModifiersExText(int modifiers)

Returns a String describing the extended modifier keys and mouse buttons, such as “Shift”, “Button1”, or “Ctrl+Shift”.

5

long getWhen()

Returns the timestamp of when this event occurred.

6

boolean isAltDown()

Returns whether or not the Alt modifier is down on this event.

7

boolean isAltGraphDown()

Returns whether or not the AltGraph modifier is down on this event.

8

boolean isConsumed()

Returns whether or not this event has been consumed.

9

boolean isControlDown()

Returns whether or not the Control modifier is down on this event.

10

boolean isMetaDown()

Returns whether or not the Meta modifier is down on this event.

11

boolean isShiftDown()

Returns whether or not the Shift modifier is down on this event.

void consume()

Consumes this event so that it will not be processed in the default manner by the source which originated it.

int getModifiers()

Returns the modifier mask for this event.

int getModifiersEx()

Returns the extended modifier mask for this event.

static String getModifiersExText(int modifiers)

Returns a String describing the extended modifier keys and mouse buttons, such as “Shift”, “Button1”, or “Ctrl+Shift”.

long getWhen()

Returns the timestamp of when this event occurred.

boolean isAltDown()

Returns whether or not the Alt modifier is down on this event.

boolean isAltGraphDown()

Returns whether or not the AltGraph modifier is down on this event.

boolean isConsumed()

Returns whether or not this event has been consumed.

boolean isControlDown()

Returns whether or not the Control modifier is down on this event.

boolean isMetaDown()

Returns whether or not the Meta modifier is down on this event.

boolean isShiftDown()

Returns whether or not the Shift modifier is down on this event.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.awt.event.ComponentEvent

  • java.awt.AWTEvent

  • java.util.EventObject

  • java.lang.Object

java.awt.event.ComponentEvent

java.awt.AWTEvent

java.util.EventObject

java.lang.Object

AWT KeyEvent Class

On entering the character the Key event is generated.There are three types of key events which are represented by the integer constants. These key events are following

  • KEY_PRESSED

  • KEY_RELASED

  • KEY_TYPED

KEY_PRESSED

KEY_RELASED

KEY_TYPED

Объявление класса

Following is the declaration for java.awt.event.KeyEvent class:

public class KeyEvent
   extends InputEvent

поле

Following are the fields for java.awt.InputEvent class:

  • static char CHAR_UNDEFINED –KEY_PRESSED and KEY_RELEASED events which do not map to a valid Unicode character use this for the keyChar value.

  • static int KEY_FIRST –The first number in the range of ids used for key events.

  • static int KEY_LAST –The last number in the range of ids used for key events.

  • static int KEY_LOCATION_LEFT –A constant indicating that the key pressed or released is in the left key location (there is more than one possible location for this key).

  • static int KEY_LOCATION_NUMPAD –A constant indicating that the key event originated on the numeric keypad or with a virtual key corresponding to the numeric keypad.

  • static int KEY_LOCATION_RIGHT — A constant indicating that the key pressed or released is in the right key location (there is more than one possible location for this key).

  • static int KEY_LOCATION_STANDARD –A constant indicating that the key pressed or released is not distinguished as the left or right version of a key, and did not originate on the numeric keypad (or did not originate with a virtual key corresponding to the numeric keypad).

  • static int KEY_LOCATION_UNKNOWN — A constant indicating that the keyLocation is indeterminate or not relevant.

  • static int KEY_PRESSED –The “key pressed” event.

  • static int KEY_RELEASED –The “key released” event.

  • static int KEY_TYPED –The “key typed” event.

  • static int VK_0 –VK_0 thru VK_9 are the same as ASCII ‘0’ thru ‘9’ (0x30 – 0x39)

  • static int VK_1

  • static int VK_2

  • static int VK_3

  • static int VK_4

  • static int VK_5

  • static int VK_6

  • static int VK_7

  • static int VK_8

  • static int VK_9

  • static int VK_A –VK_A thru VK_Z are the same as ASCII ‘A’ thru ‘Z’ (0x41 – 0x5A)

  • static int VK_ACCEPT –Constant for the Accept or Commit function key.

  • static int VK_ADD

  • static int VK_AGAIN

  • static int VK_ALL_CANDIDATES –Constant for the All Candidates function key.

  • static int VK_ALPHANUMERIC –Constant for the Alphanumeric function key.

  • static int VK_ALT

  • static int VK_ALT_GRAPH –Constant for the AltGraph function key.

  • static int VK_AMPERSAND

  • static int VK_ASTERISK

  • static int VK_AT –constant for the “@” key.

  • static int VK_B

  • static int VK_BACK_QUOTE

  • static int VK_BACK_SLASH –Constant for the back slash key, “\”

  • static int VK_BACK_SPACE

  • static int VK_BEGIN –Constant for the Begin key.

  • static int VK_BRACELEFT

  • static int VK_BRACERIGHT

  • static int VK_C

  • static int VK_CANCEL

  • static int VK_CAPS_LOCK

  • static int VK_CIRCUMFLEX –Constant for the “^” key.

  • static int VK_CLEAR

  • static int VK_CLOSE_BRACKET –Constant for the close bracket key, “]”

  • static int VK_CODE_INPUT –Constant for the Code Input function key.

  • static int VK_COLON –Constant for the “:” key.

  • static int VK_COMMA –Constant for the comma key, “,”

  • static int VK_COMPOSE –Constant for the Compose function key.

  • static int VK_CONTEXT_MENU –Constant for the Microsoft Windows Context Menu key.

  • static int VK_CONTROL

  • static int VK_CONVERT — Constant for the Convert function key.

  • static int VK_COPY

  • static int VK_CUT

  • static int VK_D

  • static int VK_DEAD_ABOVEDOT

  • static int VK_DEAD_ABOVERING

  • static int VK_DEAD_ACUTE

  • static int VK_DEAD_BREVE

  • static int VK_DEAD_CARON

  • static int VK_DEAD_CEDILLA

  • static int VK_DEAD_CIRCUMFLEX

  • static int VK_DEAD_DIAERESIS

  • static int VK_DEAD_DOUBLEACUTE

  • static int VK_DEAD_GRAVE

  • static int VK_DEAD_IOTA

  • static int VK_DEAD_MACRON

  • static int VK_DEAD_OGONEK

  • static int VK_DEAD_SEMIVOICED_SOUND

  • static int VK_DEAD_TILDE

  • static int VK_DEAD_VOICED_SOUND

  • static int VK_DECIMAL

  • static int VK_DELETE

  • static int VK_DIVIDE

  • static int VK_DOLLAR –Constant for the “$” key.

  • static int VK_DOWN — Constant for the non-numpad down arrow key.

  • static int VK_E

  • static int VK_END

  • static int VK_ENTER

  • static int VK_EQUALS –Constant for the equals key, “=”

  • static int VK_ESCAPE

  • static int VK_EURO_SIGN –Constant for the Euro currency sign key.

  • static int VK_EXCLAMATION_MARK –Constant for the “!” ключ.

  • static int VK_F

  • static int VK_F1 –Constant for the F1 function key.

  • static int VK_F10 –Constant for the F10 function key.

  • static int VK_F11 –Constant for the F11 function key.

  • static int VK_F12 –Constant for the F12 function key.

  • static int VK_F13 –Constant for the F13 function key.

  • static int VK_F14 –Constant for the F14 function key.

  • static int VK_F15 –Constant for the F15 function key.

  • static int VK_F16 –Constant for the F16 function key.

  • static int VK_F17 –Constant for the F17 function key.

  • static int VK_F18 –Constant for the F18 function key.

  • static int VK_F19 –Constant for the F19 function key.

  • static int VK_F2 –Constant for the F2 function key.

  • static int VK_F20 –Constant for the F20 function key.

  • static int VK_F21 — Constant for the F21 function key.

  • static int VK_F22 –Constant for the F22 function key.

  • static int VK_F23 –Constant for the F23 function key.

  • static int VK_F24 –Constant for the F24 function key.

  • static int VK_F3 –Constant for the F3 function key.

  • static int VK_F4 –Constant for the F4 function key.

  • static int VK_F5 — Constant for the F5 function key.

  • static int VK_F6 –Constant for the F6 function key.

  • static int VK_F7 –Constant for the F7 function key.

  • static int VK_F8 –Constant for the F8 function key.

  • static int VK_F9 –Constant for the F9 function key.

  • static int VK_FINAL

  • static int VK_FIND

  • static int VK_FULL_WIDTH –Constant for the Full-Width Characters function key.

  • static int VK_G

  • static int VK_GREATER

  • static int VK_H

  • static int VK_HALF_WIDTH –Constant for the Half-Width Characters function key.

  • static int VK_HELP

  • static int VK_HIRAGANA –Constant for the Hiragana function key.

  • static int VK_HOME

  • static int VK_I

  • static int VK_INPUT_METHOD_ON_OFF — Constant for the input method on/off key.

  • static int VK_INSERT

  • static int VK_INVERTED_EXCLAMATION_MARK –Constant for the inverted exclamation mark key.

  • static int VK_J

  • static int VK_JAPANESE_HIRAGANA –Constant for the Japanese-Hiragana function key.

  • static int VK_JAPANESE_KATAKANA –Constant for the Japanese-Katakana function key.

  • static int VK_JAPANESE_ROMAN –Constant for the Japanese-Roman function key.

  • static int VK_K

  • static int VK_KANA

  • static int VK_KANA_LOCK — Constant for the locking Kana function key.

  • static int VK_KANJI

  • static int VK_KATAKANA –Constant for the Katakana function key.

  • static int VK_KP_DOWN — Constant for the numeric keypad down arrow key.

  • static int VK_KP_LEFT –Constant for the numeric keypad left arrow key.

  • static int VK_KP_RIGHT –Constant for the numeric keypad right arrow key.

  • static int VK_KP_UP –Constant for the numeric keypad up arrow key.

  • static int VK_L

  • static int VK_LEFT –Constant for the non-numpad left arrow key.

  • static int VK_LEFT_PARENTHESIS –Constant for the “(” key.

  • static int VK_LESS

  • static int VK_M

  • static int VK_META

  • static int VK_MINUS — Constant for the minus key, “-”

  • static int VK_MODECHANGE

  • static int VK_MULTIPLY

  • static int VK_N

  • static int VK_NONCONVERT –Constant for the Don’t Convert function key.

  • static int VK_NUM_LOCK

  • static int VK_NUMBER_SIGN –Constant for the “#” key.

  • static int VK_NUMPAD0

  • static int VK_NUMPAD1

  • static int VK_NUMPAD2

  • static int VK_NUMPAD3

  • static int VK_NUMPAD4

  • static int VK_NUMPAD5

  • static int VK_NUMPAD6

  • static int VK_NUMPAD7

  • static int VK_NUMPAD8

  • static int VK_NUMPAD9

  • static int VK_O

  • static int VK_OPEN_BRACKET –Constant for the open bracket key, “[”

  • static int VK_P

  • static int VK_PAGE_DOWN

  • static int VK_PAGE_UP

  • static int VK_PASTE

  • static int VK_PAUSE

  • static int VK_PERIOD –Constant for the period key, “.”

  • static int VK_PLUS — Constant for the “+” key.

  • static int VK_PREVIOUS_CANDIDATE — Constant for the Previous Candidate function key.

  • static int VK_PRINTSCREEN

  • static int VK_PROPS

  • static int VK_Q

  • static int VK_QUOTE

  • static int VK_QUOTEDBL

  • static int VK_R

  • static int VK_RIGHT — Constant for the non-numpad right arrow key.

  • static int VK_RIGHT_PARENTHESIS –Constant for the “)” key.

  • static int VK_ROMAN_CHARACTERS –Constant for the Roman Characters function key.

  • static int VK_S

  • static int VK_SCROLL_LOCK

  • static int VK_SEMICOLON — Constant for the semicolon key, “;”

  • static int VK_SEPARATER –This constant is obsolete, and is included only for backwards compatibility.

  • static int VK_SEPARATOR –Constant for the Numpad Separator key.

  • static int VK_SHIFT

  • static int VK_SLASH — Constant for the forward slash key, “/”

  • static int VK_SPACE

  • static int VK_STOP

  • static int VK_SUBTRACT

  • static int VK_T

  • static int VK_TAB

  • static int VK_U

  • static int VK_UNDEFINED — This value is used to indicate that the keyCode is unknown.

  • static int VK_UNDERSCORE –Constant for the “_” key.

  • static int VK_UNDO

  • static int VK_UP –Constant for the non-numpad up arrow key.

  • static int VK_V

  • static int VK_W

  • static int VK_WINDOWS –Constant for the Microsoft Windows “Windows” key.

  • static int VK_X

  • static int VK_Y

  • static int VK_Z

static char CHAR_UNDEFINED –KEY_PRESSED and KEY_RELEASED events which do not map to a valid Unicode character use this for the keyChar value.

static int KEY_FIRST –The first number in the range of ids used for key events.

static int KEY_LAST –The last number in the range of ids used for key events.

static int KEY_LOCATION_LEFT –A constant indicating that the key pressed or released is in the left key location (there is more than one possible location for this key).

static int KEY_LOCATION_NUMPAD –A constant indicating that the key event originated on the numeric keypad or with a virtual key corresponding to the numeric keypad.

static int KEY_LOCATION_RIGHT — A constant indicating that the key pressed or released is in the right key location (there is more than one possible location for this key).

static int KEY_LOCATION_STANDARD –A constant indicating that the key pressed or released is not distinguished as the left or right version of a key, and did not originate on the numeric keypad (or did not originate with a virtual key corresponding to the numeric keypad).

static int KEY_LOCATION_UNKNOWN — A constant indicating that the keyLocation is indeterminate or not relevant.

static int KEY_PRESSED –The “key pressed” event.

static int KEY_RELEASED –The “key released” event.

static int KEY_TYPED –The “key typed” event.

static int VK_1

static int VK_2

static int VK_3

static int VK_4

static int VK_5

static int VK_6

static int VK_7

static int VK_8

static int VK_9

static int VK_A –VK_A thru VK_Z are the same as ASCII ‘A’ thru ‘Z’ (0x41 – 0x5A)

static int VK_ACCEPT –Constant for the Accept or Commit function key.

static int VK_ADD

static int VK_AGAIN

static int VK_ALL_CANDIDATES –Constant for the All Candidates function key.

static int VK_ALPHANUMERIC –Constant for the Alphanumeric function key.

static int VK_ALT

static int VK_ALT_GRAPH –Constant for the AltGraph function key.

static int VK_AMPERSAND

static int VK_ASTERISK

static int VK_AT –constant for the “@” key.

static int VK_B

static int VK_BACK_QUOTE

static int VK_BACK_SLASH –Constant for the back slash key, “\”

static int VK_BACK_SPACE

static int VK_BEGIN –Constant for the Begin key.

static int VK_BRACELEFT

static int VK_BRACERIGHT

static int VK_C

static int VK_CANCEL

static int VK_CAPS_LOCK

static int VK_CIRCUMFLEX –Constant for the “^” key.

static int VK_CLEAR

static int VK_CLOSE_BRACKET –Constant for the close bracket key, “]”

static int VK_CODE_INPUT –Constant for the Code Input function key.

static int VK_COLON –Constant for the “:” key.

static int VK_COMMA –Constant for the comma key, “,”

static int VK_COMPOSE –Constant for the Compose function key.

static int VK_CONTEXT_MENU –Constant for the Microsoft Windows Context Menu key.

static int VK_CONTROL

static int VK_CONVERT — Constant for the Convert function key.

static int VK_COPY

static int VK_CUT

static int VK_D

static int VK_DEAD_ABOVEDOT

static int VK_DEAD_ABOVERING

static int VK_DEAD_ACUTE

static int VK_DEAD_BREVE

static int VK_DEAD_CARON

static int VK_DEAD_CEDILLA

static int VK_DEAD_CIRCUMFLEX

static int VK_DEAD_DIAERESIS

static int VK_DEAD_DOUBLEACUTE

static int VK_DEAD_GRAVE

static int VK_DEAD_IOTA

static int VK_DEAD_MACRON

static int VK_DEAD_OGONEK

static int VK_DEAD_SEMIVOICED_SOUND

static int VK_DEAD_TILDE

static int VK_DEAD_VOICED_SOUND

static int VK_DECIMAL

static int VK_DELETE

static int VK_DIVIDE

static int VK_DOLLAR –Constant for the “$” key.

static int VK_DOWN — Constant for the non-numpad down arrow key.

static int VK_E

static int VK_END

static int VK_ENTER

static int VK_EQUALS –Constant for the equals key, “=”

static int VK_ESCAPE

static int VK_EURO_SIGN –Constant for the Euro currency sign key.

static int VK_EXCLAMATION_MARK –Constant for the “!” ключ.

static int VK_F

static int VK_F1 –Constant for the F1 function key.

static int VK_F10 –Constant for the F10 function key.

static int VK_F11 –Constant for the F11 function key.

static int VK_F12 –Constant for the F12 function key.

static int VK_F13 –Constant for the F13 function key.

static int VK_F14 –Constant for the F14 function key.

static int VK_F15 –Constant for the F15 function key.

static int VK_F16 –Constant for the F16 function key.

static int VK_F17 –Constant for the F17 function key.

static int VK_F18 –Constant for the F18 function key.

static int VK_F19 –Constant for the F19 function key.

static int VK_F2 –Constant for the F2 function key.

static int VK_F20 –Constant for the F20 function key.

static int VK_F21 — Constant for the F21 function key.

static int VK_F22 –Constant for the F22 function key.

static int VK_F23 –Constant for the F23 function key.

static int VK_F24 –Constant for the F24 function key.

static int VK_F3 –Constant for the F3 function key.

static int VK_F4 –Constant for the F4 function key.

static int VK_F5 — Constant for the F5 function key.

static int VK_F6 –Constant for the F6 function key.

static int VK_F7 –Constant for the F7 function key.

static int VK_F8 –Constant for the F8 function key.

static int VK_F9 –Constant for the F9 function key.

static int VK_FINAL

static int VK_FIND

static int VK_FULL_WIDTH –Constant for the Full-Width Characters function key.

static int VK_G

static int VK_GREATER

static int VK_H

static int VK_HALF_WIDTH –Constant for the Half-Width Characters function key.

static int VK_HELP

static int VK_HIRAGANA –Constant for the Hiragana function key.

static int VK_HOME

static int VK_I

static int VK_INPUT_METHOD_ON_OFF — Constant for the input method on/off key.

static int VK_INSERT

static int VK_INVERTED_EXCLAMATION_MARK –Constant for the inverted exclamation mark key.

static int VK_J

static int VK_JAPANESE_HIRAGANA –Constant for the Japanese-Hiragana function key.

static int VK_JAPANESE_KATAKANA –Constant for the Japanese-Katakana function key.

static int VK_JAPANESE_ROMAN –Constant for the Japanese-Roman function key.

static int VK_K

static int VK_KANA

static int VK_KANA_LOCK — Constant for the locking Kana function key.

static int VK_KANJI

static int VK_KATAKANA –Constant for the Katakana function key.

static int VK_KP_DOWN — Constant for the numeric keypad down arrow key.

static int VK_KP_LEFT –Constant for the numeric keypad left arrow key.

static int VK_KP_RIGHT –Constant for the numeric keypad right arrow key.

static int VK_KP_UP –Constant for the numeric keypad up arrow key.

static int VK_L

static int VK_LEFT –Constant for the non-numpad left arrow key.

static int VK_LEFT_PARENTHESIS –Constant for the “(” key.

static int VK_LESS

static int VK_M

static int VK_META

static int VK_MINUS — Constant for the minus key, “-”

static int VK_MODECHANGE

static int VK_MULTIPLY

static int VK_N

static int VK_NONCONVERT –Constant for the Don’t Convert function key.

static int VK_NUM_LOCK

static int VK_NUMBER_SIGN –Constant for the “#” key.

static int VK_NUMPAD0

static int VK_NUMPAD1

static int VK_NUMPAD2

static int VK_NUMPAD3

static int VK_NUMPAD4

static int VK_NUMPAD5

static int VK_NUMPAD6

static int VK_NUMPAD7

static int VK_NUMPAD8

static int VK_NUMPAD9

static int VK_O

static int VK_OPEN_BRACKET –Constant for the open bracket key, “[”

static int VK_P

static int VK_PAGE_DOWN

static int VK_PAGE_UP

static int VK_PASTE

static int VK_PAUSE

static int VK_PERIOD –Constant for the period key, “.”

static int VK_PLUS — Constant for the “+” key.

static int VK_PREVIOUS_CANDIDATE — Constant for the Previous Candidate function key.

static int VK_PRINTSCREEN

static int VK_PROPS

static int VK_Q

static int VK_QUOTE

static int VK_QUOTEDBL

static int VK_R

static int VK_RIGHT — Constant for the non-numpad right arrow key.

static int VK_RIGHT_PARENTHESIS –Constant for the “)” key.

static int VK_ROMAN_CHARACTERS –Constant for the Roman Characters function key.

static int VK_S

static int VK_SCROLL_LOCK

static int VK_SEMICOLON — Constant for the semicolon key, “;”

static int VK_SEPARATER –This constant is obsolete, and is included only for backwards compatibility.

static int VK_SEPARATOR –Constant for the Numpad Separator key.

static int VK_SHIFT

static int VK_SLASH — Constant for the forward slash key, “/”

static int VK_SPACE

static int VK_STOP

static int VK_SUBTRACT

static int VK_T

static int VK_TAB

static int VK_U

static int VK_UNDEFINED — This value is used to indicate that the keyCode is unknown.

static int VK_UNDERSCORE –Constant for the “_” key.

static int VK_UNDO

static int VK_UP –Constant for the non-numpad up arrow key.

static int VK_V

static int VK_W

static int VK_WINDOWS –Constant for the Microsoft Windows “Windows” key.

static int VK_X

static int VK_Y

static int VK_Z

Конструкторы классов

SN Конструктор и описание
1

KeyEvent(Component source, int id, long when, int modifiers, int keyCode)

Устаревшее. as of JDK1.1

2

KeyEvent(Component source, int id, long when, int modifiers, int keyCode, char keyChar)

Constructs a KeyEvent object.

3

KeyEvent(Component source, int id, long when, int modifiers, int keyCode, char keyChar, int keyLocation)

KeyEvent(Component source, int id, long when, int modifiers, int keyCode)

Устаревшее. as of JDK1.1

KeyEvent(Component source, int id, long when, int modifiers, int keyCode, char keyChar)

Constructs a KeyEvent object.

KeyEvent(Component source, int id, long when, int modifiers, int keyCode, char keyChar, int keyLocation)

Методы класса

SN Метод и описание
1

char getKeyChar()

Returns the character associated with the key in this event.

2

int getKeyCode()

Returns the integer keyCode associated with the key in this event.

3

int getKeyLocation()

Returns the location of the key that originated this key event.

4

static String getKeyModifiersText(int modifiers)

Returns a String describing the modifier key(s), such as “Shift”, or “Ctrl+Shift”.

5

static String getKeyText(int keyCode)

Returns a String describing the keyCode, such as “HOME”, “F1” or “A”.

6

boolean isActionKey()

Returns whether the key in this event is an “action” key.

7

String paramString()

Returns a parameter string identifying this event.

8

void setKeyChar(char keyChar)

Set the keyChar value to indicate a logical character.

9

void setKeyCode(int keyCode)

Set the keyCode value to indicate a physical key.

10

void setModifiers(int modifiers)

Устаревшее. as of JDK1.1.4

char getKeyChar()

Returns the character associated with the key in this event.

int getKeyCode()

Returns the integer keyCode associated with the key in this event.

int getKeyLocation()

Returns the location of the key that originated this key event.

static String getKeyModifiersText(int modifiers)

Returns a String describing the modifier key(s), such as “Shift”, or “Ctrl+Shift”.

static String getKeyText(int keyCode)

Returns a String describing the keyCode, such as “HOME”, “F1” or “A”.

boolean isActionKey()

Returns whether the key in this event is an “action” key.

String paramString()

Returns a parameter string identifying this event.

void setKeyChar(char keyChar)

Set the keyChar value to indicate a logical character.

void setKeyCode(int keyCode)

Set the keyCode value to indicate a physical key.

void setModifiers(int modifiers)

Устаревшее. as of JDK1.1.4

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.awt.event.InputEvent

  • java.awt.event.ComponentEvent

  • java.awt.AWTEvent

  • java.util.EventObject

  • java.lang.Object

java.awt.event.InputEvent

java.awt.event.ComponentEvent

java.awt.AWTEvent

java.util.EventObject

java.lang.Object

AWT MouseEvent Class

Это событие указывает, что действие мыши произошло в компоненте. This low-level event is generated by a component object for Mouse Events and Mouse motion events.

  • a mouse button is pressed

  • a mouse button is released

  • a mouse button is clicked (pressed and released)

  • a mouse cursor enters the unobscured part of component’s geometry

  • a mouse cursor exits the unobscured part of component’s geometry

  • a mouse is moved

  • the mouse is dragged

a mouse button is pressed

a mouse button is released

a mouse button is clicked (pressed and released)

a mouse cursor enters the unobscured part of component’s geometry

a mouse cursor exits the unobscured part of component’s geometry

a mouse is moved

the mouse is dragged

Объявление класса

Following is the declaration for java.awt.event.MouseEvent class:

public class MouseEvent
   extends InputEvent

поле

Following are the fields for java.awt.event.MouseEvent class:

  • static int BUTTON1 –Indicates mouse button #1; used by getButton()

  • static int BUTTON2 –Indicates mouse button #2; used by getButton()

  • static int BUTTON3 –Indicates mouse button #3; used by getButton()

  • static int MOUSE_CLICKED –The “mouse clicked” event

  • static int MOUSE_DRAGGED –The “mouse dragged” event

  • static int MOUSE_ENTERED –The “mouse entered” event

  • static int MOUSE_EXITED –The “mouse exited” event

  • static int MOUSE_FIRST –The first number in the range of ids used for mouse events

  • static int MOUSE_LAST — The last number in the range of ids used for mouse events

  • static int MOUSE_MOVED –The “mouse moved” event

  • static int MOUSE_PRESSED — The “mouse pressed” event

  • static int MOUSE_RELEASED –The “mouse released” event

  • static int MOUSE_WHEEL –The “mouse wheel” event

  • static int NOBUTTON –Indicates no mouse buttons; used by getButton()

  • static int VK_WINDOWS –Constant for the Microsoft Windows “Windows” key.

static int BUTTON1 –Indicates mouse button #1; used by getButton()

static int BUTTON2 –Indicates mouse button #2; used by getButton()

static int BUTTON3 –Indicates mouse button #3; used by getButton()

static int MOUSE_CLICKED –The “mouse clicked” event

static int MOUSE_DRAGGED –The “mouse dragged” event

static int MOUSE_ENTERED –The “mouse entered” event

static int MOUSE_EXITED –The “mouse exited” event

static int MOUSE_FIRST –The first number in the range of ids used for mouse events

static int MOUSE_LAST — The last number in the range of ids used for mouse events

static int MOUSE_MOVED –The “mouse moved” event

static int MOUSE_PRESSED — The “mouse pressed” event

static int MOUSE_RELEASED –The “mouse released” event

static int MOUSE_WHEEL –The “mouse wheel” event

static int NOBUTTON –Indicates no mouse buttons; used by getButton()

static int VK_WINDOWS –Constant for the Microsoft Windows “Windows” key.

Конструкторы классов

SN Конструктор и описание
1

MouseEvent(Component source, int id, long when, int modifiers, int x, int y, int clickCount, boolean popupTrigger)

Constructs a MouseEvent object with the specified source component, type, modifiers, coordinates, and click count.

2

MouseEvent(Component source, int id, long when, int modifiers, int x, int y, int clickCount, boolean popupTrigger, int button)

Constructs a MouseEvent object with the specified source component, type, modifiers, coordinates, and click count.

3

MouseEvent(Component source, int id, long when, int modifiers, int x, int y, int xAbs, int yAbs, int clickCount, boolean popupTrigger, int button)

Constructs a MouseEvent object with the specified source component, type, modifiers, coordinates, absolute coordinates, and click count.

MouseEvent(Component source, int id, long when, int modifiers, int x, int y, int clickCount, boolean popupTrigger)

Constructs a MouseEvent object with the specified source component, type, modifiers, coordinates, and click count.

MouseEvent(Component source, int id, long when, int modifiers, int x, int y, int clickCount, boolean popupTrigger, int button)

Constructs a MouseEvent object with the specified source component, type, modifiers, coordinates, and click count.

MouseEvent(Component source, int id, long when, int modifiers, int x, int y, int xAbs, int yAbs, int clickCount, boolean popupTrigger, int button)

Constructs a MouseEvent object with the specified source component, type, modifiers, coordinates, absolute coordinates, and click count.

Методы класса

SN Метод и описание
1

int getButton()

Возвращает, если, если таковые имеются, кнопки мыши изменили состояние.

2

int getClickCount()

Returns the number of mouse clicks associated with this event.

3

Point getLocationOnScreen()

Returns the absolute x, y position of the event.

4

static String getMouseModifiersText(int modifiers)

Returns a String describing the modifier keys and mouse buttons that were down during the event, such as “Shift”, or “Ctrl+Shift”.

5

Point getPoint()

Returns the x,y position of the event relative to the source component.

6

int getX()

Returns the horizontal x position of the event relative to the source component.

7

int getXOnScreen()

Returns the absolute horizontal x position of the event.

8

int getY()

Returns the vertical y position of the event relative to the source component.

9

int getYOnScreen()

Returns the absolute vertical y position of the event.

10

boolean isPopupTrigger() Returns whether or not this mouse event is the popup menu trigger event for the platform.

11

String paramString()

Returns a parameter string identifying this event.

12

void translatePoint(int x, int y)

Translates the event’s coordinates to a new position by adding specified x (horizontal) and y (vertical) offsets.

int getButton()

Возвращает, если, если таковые имеются, кнопки мыши изменили состояние.

int getClickCount()

Returns the number of mouse clicks associated with this event.

Point getLocationOnScreen()

Returns the absolute x, y position of the event.

static String getMouseModifiersText(int modifiers)

Returns a String describing the modifier keys and mouse buttons that were down during the event, such as “Shift”, or “Ctrl+Shift”.

Point getPoint()

Returns the x,y position of the event relative to the source component.

int getX()

Returns the horizontal x position of the event relative to the source component.

int getXOnScreen()

Returns the absolute horizontal x position of the event.

int getY()

Returns the vertical y position of the event relative to the source component.

int getYOnScreen()

Returns the absolute vertical y position of the event.

boolean isPopupTrigger() Returns whether or not this mouse event is the popup menu trigger event for the platform.

String paramString()

Returns a parameter string identifying this event.

void translatePoint(int x, int y)

Translates the event’s coordinates to a new position by adding specified x (horizontal) and y (vertical) offsets.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.awt.event.InputEvent

  • java.awt.event.ComponentEvent

  • java.awt.AWTEvent

  • java.util.EventObject

  • java.lang.Object

java.awt.event.InputEvent

java.awt.event.ComponentEvent

java.awt.AWTEvent

java.util.EventObject

java.lang.Object

AWT TextEvent Class

The object of this class represents the text events.The TextEvent is generated when character is entered in the text fields or text area. The TextEvent instance does not include the characters currently in the text component that generated the event rather we are provided with other methods to retrieve that information.

Объявление класса

Following is the declaration for java.awt.event.TextEvent class:

public class TextEvent
   extends AWTEvent

поле

Following are the fields for java.awt.event.TextEvent class:

  • static int TEXT_FIRST –The first number in the range of ids used for text events.

  • static int TEXT_LAST –The last number in the range of ids used for text events.

  • static int TEXT_VALUE_CHANGED –This event id indicates that object’s text changed.

static int TEXT_FIRST –The first number in the range of ids used for text events.

static int TEXT_LAST –The last number in the range of ids used for text events.

static int TEXT_VALUE_CHANGED –This event id indicates that object’s text changed.

Конструкторы классов

<0tr>

SN Конструктор и описание
1

TextEvent(Object source, int id)

Constructs a TextEvent object.

TextEvent(Object source, int id)

Constructs a TextEvent object.

Методы класса

SN Метод и описание
1

String paramString()

Returns a parameter string identifying this text event.

String paramString()

Returns a parameter string identifying this text event.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.awt.AWTEvent

  • java.util.EventObject

  • java.lang.Object

java.awt.AWTEvent

java.util.EventObject

java.lang.Object

AWT WindowEvent Class

The object of this class represents the change in state of a window.This low-level event is generated by a Window object when it is opened, closed, activated, deactivated, iconified, or deiconified, or when focus is transfered into or out of the Window.

Объявление класса

Following is the declaration for java.awt.event.WindowEvent class:

public class WindowEvent
   extends ComponentEvent

поле

Following are the fields for java.awt.event.WindowEvent class:

  • static int WINDOW_ACTIVATED –The window-activated event type.

  • static int WINDOW_CLOSED — The window closed event.

  • static int WINDOW_CLOSING — The “window is closing” event.

  • static int WINDOW_DEACTIVATED — The window-deactivated event type.

  • static int WINDOW_DEICONIFIED — The window deiconified event type.

  • static int WINDOW_FIRST — The first number in the range of ids used for window events.

  • static int WINDOW_GAINED_FOCUS — The window-gained-focus event type.

  • static int WINDOW_ICONIFIED — The window iconified event.

  • static int WINDOW_LAST — The last number in the range of ids used for window events.

  • static int WINDOW_LOST_FOCUS — The window-lost-focus event type.

  • static int WINDOW_OPENED — The window opened event.

  • static int WINDOW_STATE_CHANGED — The window-state-changed event type.

static int WINDOW_ACTIVATED –The window-activated event type.

static int WINDOW_CLOSED — The window closed event.

static int WINDOW_CLOSING — The “window is closing” event.

static int WINDOW_DEACTIVATED — The window-deactivated event type.

static int WINDOW_DEICONIFIED — The window deiconified event type.

static int WINDOW_FIRST — The first number in the range of ids used for window events.

static int WINDOW_GAINED_FOCUS — The window-gained-focus event type.

static int WINDOW_ICONIFIED — The window iconified event.

static int WINDOW_LAST — The last number in the range of ids used for window events.

static int WINDOW_LOST_FOCUS — The window-lost-focus event type.

static int WINDOW_OPENED — The window opened event.

static int WINDOW_STATE_CHANGED — The window-state-changed event type.

Конструкторы классов

<0tr>

SN Конструктор и описание
1

WindowEvent(Window source, int id)

Constructs a WindowEvent object.

2

WindowEvent(Window source, int id, int oldState, int newState)

Constructs a WindowEvent object with the specified previous and new window states.

3

WindowEvent(Window source, int id, Window opposite)

Constructs a WindowEvent object with the specified opposite Window.

4

WindowEvent(Window source, int id, Window opposite, int oldState, int newState)

Constructs a WindowEvent object.

WindowEvent(Window source, int id)

Constructs a WindowEvent object.

WindowEvent(Window source, int id, int oldState, int newState)

Constructs a WindowEvent object with the specified previous and new window states.

WindowEvent(Window source, int id, Window opposite)

Constructs a WindowEvent object with the specified opposite Window.

WindowEvent(Window source, int id, Window opposite, int oldState, int newState)

Constructs a WindowEvent object.

Методы класса

SN Метод и описание
1

int getNewState()

For WINDOW_STATE_CHANGED events returns the new state of the window.

2

int getOldState()

For WINDOW_STATE_CHANGED events returns the previous state of the window.

3

Window getOppositeWindow()

Returns the other Window involved in this focus or activation change.

4

Window getWindow()

Returns the originator of the event.

5

String paramString()

Returns a parameter string identifying this event.

int getNewState()

For WINDOW_STATE_CHANGED events returns the new state of the window.

int getOldState()

For WINDOW_STATE_CHANGED events returns the previous state of the window.

Window getOppositeWindow()

Returns the other Window involved in this focus or activation change.

Window getWindow()

Returns the originator of the event.

String paramString()

Returns a parameter string identifying this event.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.awt.event.ComponentEvent

  • java.awt.AWTEvent

  • java.util.EventObject

  • java.lang.Object

java.awt.event.ComponentEvent

java.awt.AWTEvent

java.util.EventObject

java.lang.Object

AWT AdjustmentEvent Class

Вступление

The Class AdjustmentEvent represents adjustment event emitted by Adjustable objects.

Объявление класса

Following is the declaration for java.awt.event.AdjustmentEvent class:

public class AdjustmentEvent
   extends AWTEvent

поле

Following are the fields for java.awt.Component class:

  • static int ADJUSTMENT_FIRST — Marks the first integer id for the range of adjustment event ids.

  • static int ADJUSTMENT_LAST — Marks the last integer id for the range of adjustment event ids.

  • static int ADJUSTMENT_VALUE_CHANGED — The adjustment value changed event.

  • static int BLOCK_DECREMENT — The block decrement adjustment type.

  • static int BLOCK_INCREMENT — The block increment adjustment type.

  • static int TRACK — The absolute tracking adjustment type.

  • static int UNIT_DECREMENT — The unit decrement adjustment type.

  • static int UNIT_INCREMENT — The unit increment adjustment type.

static int ADJUSTMENT_FIRST — Marks the first integer id for the range of adjustment event ids.

static int ADJUSTMENT_LAST — Marks the last integer id for the range of adjustment event ids.

static int ADJUSTMENT_VALUE_CHANGED — The adjustment value changed event.

static int BLOCK_DECREMENT — The block decrement adjustment type.

static int BLOCK_INCREMENT — The block increment adjustment type.

static int TRACK — The absolute tracking adjustment type.

static int UNIT_DECREMENT — The unit decrement adjustment type.

static int UNIT_INCREMENT — The unit increment adjustment type.

Конструкторы классов

SN Конструктор и описание
1

AdjustmentEvent(Adjustable source, int id, int type, int value)

Constructs an AdjustmentEvent object with the specified Adjustable source, event type, adjustment type, and value.

2

AdjustmentEvent(Adjustable source, int id, int type, int value, boolean isAdjusting)

Constructs an AdjustmentEvent object with the specified Adjustable source, event type, adjustment type, and value.

AdjustmentEvent(Adjustable source, int id, int type, int value)

Constructs an AdjustmentEvent object with the specified Adjustable source, event type, adjustment type, and value.

AdjustmentEvent(Adjustable source, int id, int type, int value, boolean isAdjusting)

Constructs an AdjustmentEvent object with the specified Adjustable source, event type, adjustment type, and value.

Методы класса

SN Метод и описание
1

Adjustable getAdjustable()

Returns the Adjustable object where this event originated.

2

int getAdjustmentType()

Returns the type of adjustment which caused the value changed event.

3

int getValue()

Returns the current value in the adjustment event.

4

boolean getValueIsAdjusting()

Returns true if this is one of multiple adjustment events.

5

String paramString()

Returns a string representing the state of this Event.

Adjustable getAdjustable()

Returns the Adjustable object where this event originated.

int getAdjustmentType()

Returns the type of adjustment which caused the value changed event.

int getValue()

Returns the current value in the adjustment event.

boolean getValueIsAdjusting()

Returns true if this is one of multiple adjustment events.

String paramString()

Returns a string representing the state of this Event.

Методы унаследованы

This interface inherits methods from the following classes:

  • java.awt.AWTEvent

  • java.util.EventObject

  • java.lang.Object

java.awt.AWTEvent

java.util.EventObject

java.lang.Object

AWT ComponentEvent Class

Вступление

The Class ComponentEvent represents that a component moved, changed size, or changed visibility

Объявление класса

Following is the declaration for java.awt.event.ComponentEvent class:

public class ComponentEvent
   extends AWTEvent

поле

Following are the fields for java.awt.Component class:

  • static int COMPONENT_FIRST — The first number in the range of ids used for component events.

  • static int COMPONENT_HIDDEN –This event indicates that the component was rendered invisible.

  • static int COMPONENT_LAST — The last number in the range of ids used for component events.

  • static int COMPONENT_MOVED — This event indicates that the component’s position changed.

  • static int COMPONENT_RESIZED — This event indicates that the component’s size changed.

  • static int COMPONENT_SHOWN — This event indicates that the component was made visible.

static int COMPONENT_FIRST — The first number in the range of ids used for component events.

static int COMPONENT_HIDDEN –This event indicates that the component was rendered invisible.

static int COMPONENT_LAST — The last number in the range of ids used for component events.

static int COMPONENT_MOVED — This event indicates that the component’s position changed.

static int COMPONENT_RESIZED — This event indicates that the component’s size changed.

static int COMPONENT_SHOWN — This event indicates that the component was made visible.

Конструкторы классов

SN Конструктор и описание
1

ComponentEvent(Component source, int id)

Constructs a ComponentEvent object.

ComponentEvent(Component source, int id)

Constructs a ComponentEvent object.

Методы класса

SN Метод и описание
1

Component getComponent()

Returns the originator of the event.

2

String paramString()

Returns a parameter string identifying this event.

Component getComponent()

Returns the originator of the event.

String paramString()

Returns a parameter string identifying this event.

Методы унаследованы

This interface inherits methods from the following classes:

  • java.awt.AWTEvent

  • java.util.EventObject

  • java.lang.Object

java.awt.AWTEvent

java.util.EventObject

java.lang.Object

AWT ContainerEvent Class

Вступление

The Class ContainerEvent represents that a container’s contents changed because a component was added or removed.

Объявление класса

Following is the declaration for java.awt.event.ContainerEvent class:

public class ContainerEvent
   extends ComponentEvent

поле

Following are the fields for java.awt.Component class:

  • static int COMPONENT_ADDED — This event indicates that a component was added to the container.

  • static int COMPONENT_REMOVED — This event indicates that a component was removed from the container.

  • static int CONTAINER_FIRST — The first number in the range of ids used for container events.

  • static int CONTAINER_LAST — The last number in the range of ids used for container events.

static int COMPONENT_ADDED — This event indicates that a component was added to the container.

static int COMPONENT_REMOVED — This event indicates that a component was removed from the container.

static int CONTAINER_FIRST — The first number in the range of ids used for container events.

static int CONTAINER_LAST — The last number in the range of ids used for container events.

Конструкторы классов

Методы класса

SN Конструктор и описание
1

ContainerEvent(Component source, int id, Component child)

Constructs a ContainerEvent object.

ContainerEvent(Component source, int id, Component child)

Constructs a ContainerEvent object.

SN Метод и описание
1

Component getChild()

Returns the component that was affected by the event.

2

Container getContainer()

Returns the originator of the event.

3

String paramString()

Returns a parameter string identifying this event.

Component getChild()

Returns the component that was affected by the event.

Container getContainer()

Returns the originator of the event.

String paramString()

Returns a parameter string identifying this event.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.awt.ComponentEvent

  • java.awt.AWTEvent

  • java.util.EventObject

  • java.lang.Object

java.awt.ComponentEvent

java.awt.AWTEvent

java.util.EventObject

java.lang.Object

AWT MouseMotionEvent Class

Вступление

The interface MouseMotionEvent indicates a mouse action occurred in a component. This low-level event is generated by a component object when mouse is dragged or moved.

Объявление класса

Following is the declaration for java.awt.event.MouseMotionEvent Class:

public class MouseMotionEvent
   extends InputEvent

Методы интерфейса

SN Метод и описание
1

void mouseDragged(MouseEvent e)

Invoked when a mouse button is pressed on a component and then dragged.

2

void mouseMoved(MouseEvent e)

Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed.

void mouseDragged(MouseEvent e)

Invoked when a mouse button is pressed on a component and then dragged.

void mouseMoved(MouseEvent e)

Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed.

Методы унаследованы

This interface inherits methods from the following classes:

  • java.awt.event.InputEvent

  • java.awt.event.ComponentEvent

  • java.awt.AWTEvent

  • java.util.EventObject

  • java.lang.Object

java.awt.event.InputEvent

java.awt.event.ComponentEvent

java.awt.AWTEvent

java.util.EventObject

java.lang.Object

AWT PaintEvent Class

Вступление

The Class PaintEvent used to ensure that paint/update method calls are serialized along with the other events delivered from the event queue

Объявление класса

Following is the declaration for java.awt.event.PaintEvent class:

public class PaintEvent
   extends ComponentEvent

поле

Following are the fields for java.awt.Component class:

  • static int PAINT — The paint event type.

  • static int PAINT_FIRST — Marks the first integer id for the range of paint event ids.

  • static int PAINT_LAST — Marks the last integer id for the range of paint event ids.

  • static int UPDATE — The update event type.

static int PAINT — The paint event type.

static int PAINT_FIRST — Marks the first integer id for the range of paint event ids.

static int PAINT_LAST — Marks the last integer id for the range of paint event ids.

static int UPDATE — The update event type.

Конструкторы классов

SN Конструктор и описание
1

PaintEvent(Component source, int id, Rectangle updateRect)

Constructs a PaintEvent object with the specified source component and type.

PaintEvent(Component source, int id, Rectangle updateRect)

Constructs a PaintEvent object with the specified source component and type.

Методы класса

SN Метод и описание
1

Rectangle getUpdateRect()

Returns the rectangle representing the area which needs to be repainted in response to this event.

2

String paramString()

Returns a parameter string identifying this event.

3

void setUpdateRect(Rectangle updateRect)

Sets the rectangle representing the area which needs to be repainted in response to this event.

Rectangle getUpdateRect()

Returns the rectangle representing the area which needs to be repainted in response to this event.

String paramString()

Returns a parameter string identifying this event.

void setUpdateRect(Rectangle updateRect)

Sets the rectangle representing the area which needs to be repainted in response to this event.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.awt.ComponentEvent

  • java.awt.AWTEvent

  • java.util.EventObject

  • java.lang.Object

java.awt.ComponentEvent

java.awt.AWTEvent

java.util.EventObject

java.lang.Object

Слушатели событий AWT

Слушатель событий представляет интерфейсы, отвечающие за обработку событий. Java предоставляет нам различные классы прослушивателей событий, но мы обсудим те, которые используются чаще. Каждый метод метода прослушивателя событий имеет единственный аргумент в качестве объекта, который является подклассом класса EventObject. Например, методы прослушивателя событий мыши будут принимать экземпляр MouseEvent, где MouseEvent является производным от EventObject.

Интерфейс EventListner

Это интерфейс маркера, который должен расширять каждый интерфейс слушателя. Этот класс определен в пакете java.util.

Объявление класса

Ниже приводится объявление для интерфейса java.util.EventListener :

public interface EventListener

Интерфейсы прослушивания событий AWT:

Ниже приведен список часто используемых слушателей событий.

AWT ActionListener Interface

The class which processes the ActionEvent should implement this interface.The object of that class must be registered with a component. The object can be registered using the addActionListener() method. When the action event occurs, that object’s actionPerformed method is invoked.

Объявление интерфейса

Following is the declaration for java.awt.event.ActionListener interface:

public interface ActionListener
   extends EventListener

Методы интерфейса

SN Метод и описание
1

void actionPerformed(ActionEvent e)

Invoked when an action occurs.

void actionPerformed(ActionEvent e)

Invoked when an action occurs.

Методы унаследованы

This interface inherits methods from the following interfaces:

  • java.awt.EventListener

java.awt.EventListener

ActionListener Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtListenerDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtListenerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtListenerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtListenerDemo  awtListenerDemo = new AwtListenerDemo();  
      awtListenerDemo.showActionListenerDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
   
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showActionListenerDemo(){
      headerLabel.setText("Listener in action: ActionListener");      

      ScrollPane panel = new ScrollPane();      
      panel.setBackground(Color.magenta);            

      Button okButton = new Button("OK");

      okButton.addActionListener(new CustomActionListener());        
      panel.add(okButton);
      controlPanel.add(panel);

      mainFrame.setVisible(true); 
   }

   class CustomActionListener implements ActionListener{

      public void actionPerformed(ActionEvent e) {
         statusLabel.setText("Ok Button Clicked.");
      }
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo

Проверьте следующий вывод

AWT ActionListener

AWT ComponentListener Interface

The class which processes the ComponentEvent should implement this interface.The object of that class must be registered with a component. The object can be registered using the addComponentListener() method. Component event are raised for information only.

Объявление интерфейса

Following is the declaration for java.awt.event.ComponentListener interface:

public interface ComponentListener
   extends EventListener

Методы интерфейса

SN Метод и описание
1

void componentHidden(ComponentEvent e)

Invoked when the component has been made invisible.

2

void componentMoved(ComponentEvent e)

Invoked when the component’s position changes.

3

void componentResized(ComponentEvent e)

Invoked when the component’s size changes.

4

void componentShown(ComponentEvent e)

Invoked when the component has been made visible.

void componentHidden(ComponentEvent e)

Invoked when the component has been made invisible.

void componentMoved(ComponentEvent e)

Invoked when the component’s position changes.

void componentResized(ComponentEvent e)

Invoked when the component’s size changes.

void componentShown(ComponentEvent e)

Invoked when the component has been made visible.

Методы унаследованы

This interface inherits methods from the following interfaces:

  • java.awt.EventListener

java.awt.EventListener

ComponentListener Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtListenerDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtListenerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtListenerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtListenerDemo  awtListenerDemo = new AwtListenerDemo();  
      awtListenerDemo.showComponentListenerDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
   
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showComponentListenerDemo(){
      headerLabel.setText("Listener in action: ComponentListener");      

      ScrollPane panel = new ScrollPane();      
      panel.setBackground(Color.magenta);            

      Label msglabel = new Label();
      msglabel.setAlignment(Label.CENTER);
      msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");
      panel.add(msglabel);

      msglabel.addComponentListener(new CustomComponentListener());      
      controlPanel.add(panel);
      mainFrame.setVisible(true);  
   }

   class CustomComponentListener implements ComponentListener {

      public void componentResized(ComponentEvent e) {
         statusLabel.setText(statusLabel.getText() 
         + e.getComponent().getClass().getSimpleName() + " resized. ");
      }

      public void componentMoved(ComponentEvent e) {
         statusLabel.setText(statusLabel.getText() 
         + e.getComponent().getClass().getSimpleName() + " moved. ");
      }

      public void componentShown(ComponentEvent e) {
         statusLabel.setText(statusLabel.getText() 
         + e.getComponent().getClass().getSimpleName() + " shown. ");
      }

      public void componentHidden(ComponentEvent e) {
         statusLabel.setText(statusLabel.getText() 
         + e.getComponent().getClass().getSimpleName() + " hidden. ");
      }
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo

Проверьте следующий вывод

AWT ComponentListener

AWT ItemListener Interface

The class which processes the ItemEvent should implement this interface.The object of that class must be registered with a component. The object can be registered using the addItemListener() method. When the action event occurs, that object’s itemStateChanged method is invoked.

Объявление интерфейса

Following is the declaration for java.awt.event.ItemListener interface:

public interface ItemListener
   extends EventListener

Методы интерфейса

SN Метод и описание
1

void itemStateChanged(ItemEvent e)

Invoked when an item has been selected or deselected by the user.

void itemStateChanged(ItemEvent e)

Invoked when an item has been selected or deselected by the user.

Методы унаследованы

This interface inherits methods from the following interfaces:

  • java.awt.EventListener

java.awt.EventListener

ItemListener Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtListenerDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtListenerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtListenerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtListenerDemo  awtListenerDemo = new AwtListenerDemo();  
      awtListenerDemo.showItemListenerDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
   
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showItemListenerDemo(){
      headerLabel.setText("Listener in action: ItemListener");      
      Checkbox chkApple = new Checkbox("Apple");
      Checkbox chkMango = new Checkbox("Mango");
      Checkbox chkPeer = new Checkbox("Peer");
      
      chkApple.addItemListener(new CustomItemListener());
      chkMango.addItemListener(new CustomItemListener());
      chkPeer.addItemListener(new CustomItemListener());

      controlPanel.add(chkApple);
      controlPanel.add(chkMango);
      controlPanel.add(chkPeer);               
      mainFrame.setVisible(true); 
   }

   class CustomItemListener implements ItemListener {
      public void itemStateChanged(ItemEvent e) {
         statusLabel.setText(e.getItem()
         +" Checkbox: " 
         + (e.getStateChange()==1?"checked":"unchecked"));
      }    
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo

Проверьте следующий вывод

AWT ItemListener

AWT KeyListener Interface

The class which processes the KeyEvent should implement this interface.The object of that class must be registered with a component. The object can be registered using the addKeyListener() method.

Объявление интерфейса

Following is the declaration for java.awt.event.KeyListener interface:

public interface KeyListener
   extends EventListener

Методы интерфейса

SN Метод и описание
1

void keyPressed(KeyEvent e)

Invoked when a key has been pressed.

2

void keyReleased(KeyEvent e)

Invoked when a key has been released.

3

void keyTyped(KeyEvent e)

Invoked when a key has been typed.

void keyPressed(KeyEvent e)

Invoked when a key has been pressed.

void keyReleased(KeyEvent e)

Invoked when a key has been released.

void keyTyped(KeyEvent e)

Invoked when a key has been typed.

Методы унаследованы

This interface inherits methods from the following interfaces:

  • java.awt.EventListener

java.awt.EventListener

KeyListener Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtListenerDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtListenerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;
   private TextField textField;
   
   public AwtListenerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtListenerDemo  awtListenerDemo = new AwtListenerDemo();  
      awtListenerDemo.showKeyListenerDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
   
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showKeyListenerDemo(){
      headerLabel.setText("Listener in action: KeyListener");      

      textField  = new TextField(10);

      textField.addKeyListener(new CustomKeyListener());
      Button okButton = new Button("OK");
      okButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            statusLabel.setText("Entered text: " + textField.getText());                
         }
      });

      controlPanel.add(textField);
      controlPanel.add(okButton);    
      mainFrame.setVisible(true);  
   }

   class CustomKeyListener implements KeyListener{
      public void keyTyped(KeyEvent e) {           
      }

      public void keyPressed(KeyEvent e) {
         if(e.getKeyCode() == KeyEvent.VK_ENTER){
            statusLabel.setText("Entered text: " + textField.getText());
         }
      }

      public void keyReleased(KeyEvent e) {            
      }    
   } 
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo

Проверьте следующий вывод

AWT KeyListener

AWT MouseListener Interface

The class which processes the MouseEvent should implement this interface.The object of that class must be registered with a component. The object can be registered using the addMouseListener() method.

Объявление интерфейса

Following is the declaration for java.awt.event.MouseListener interface:

public interface MouseListener
   extends EventListener

Методы интерфейса

SN Метод и описание
1

void mouseClicked(MouseEvent e)

Invoked when the mouse button has been clicked (pressed and released) on a component.

2

void mouseEntered(MouseEvent e)

Invoked when the mouse enters a component.

3

void mouseExited(MouseEvent e)

Invoked when the mouse exits a component.

4

void mousePressed(MouseEvent e)

Invoked when a mouse button has been pressed on a component.

5

void mouseReleased(MouseEvent e)

Invoked when a mouse button has been released on a component.

void mouseClicked(MouseEvent e)

Invoked when the mouse button has been clicked (pressed and released) on a component.

void mouseEntered(MouseEvent e)

Invoked when the mouse enters a component.

void mouseExited(MouseEvent e)

Invoked when the mouse exits a component.

void mousePressed(MouseEvent e)

Invoked when a mouse button has been pressed on a component.

void mouseReleased(MouseEvent e)

Invoked when a mouse button has been released on a component.

Методы унаследованы

This interface inherits methods from the following interfaces:

  • java.awt.EventListener

java.awt.EventListener

MouseListener Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtListenerDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtListenerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtListenerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtListenerDemo  awtListenerDemo = new AwtListenerDemo();  
      awtListenerDemo.showMouseListenerDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
   
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showMouseListenerDemo(){
      headerLabel.setText("Listener in action: MouseListener");      

      Panel panel = new Panel();      
      panel.setBackground(Color.magenta);
      panel.setLayout(new FlowLayout());        
      panel.addMouseListener(new CustomMouseListener());

      Label msglabel = new Label();
      msglabel.setAlignment(Label.CENTER);
      msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");

      msglabel.addMouseListener(new CustomMouseListener());
      panel.add(msglabel);

      controlPanel.add(panel);

      mainFrame.setVisible(true);  
   }

   class CustomMouseListener implements MouseListener{

      public void mouseClicked(MouseEvent e) {
         statusLabel.setText("Mouse Clicked: ("
         +e.getX()+", "+e.getY() +")");
      }   

      public void mousePressed(MouseEvent e) {
      }

      public void mouseReleased(MouseEvent e) {
      }

      public void mouseEntered(MouseEvent e) {
      }

      public void mouseExited(MouseEvent e) {
      }
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo

Проверьте следующий вывод

AWT MouseListener

AWT TextListener Interface

The class which processes the TextEvent should implement this interface.The object of that class must be registered with a component. The object can be registered using the addTextListener() method.

Объявление интерфейса

Following is the declaration for java.awt.event.TextListener interface:

public interface TextListener
   extends EventListener

Методы интерфейса

SN Метод и описание
1

void textValueChanged(TextEvent e)

Invoked when the value of the text has changed.

void textValueChanged(TextEvent e)

Invoked when the value of the text has changed.

Методы унаследованы

This interface inherits methods from the following interfaces:

  • java.awt.EventListener

java.awt.EventListener

TextListener Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtListenerDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtListenerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;
   private TextField textField;

   public AwtListenerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtListenerDemo  awtListenerDemo = new AwtListenerDemo();  
      awtListenerDemo.showTextListenerDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
   
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showTextListenerDemo(){
      headerLabel.setText("Listener in action: TextListener");      

      textField  = new TextField(10);

      textField.addTextListener(new CustomTextListener());
      Button okButton = new Button("OK");
      okButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            statusLabel.setText("Entered text: " 
            + textField.getText());                
         }
      });

      controlPanel.add(textField);
      controlPanel.add(okButton);    
      mainFrame.setVisible(true);  
   }

   class CustomTextListener implements TextListener {
      public void textValueChanged(TextEvent e) {
         statusLabel.setText("Entered text: " + textField.getText());               
      }
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo

Проверьте следующий вывод

AWT TextListener

AWT WindowListener Interface

The class which processes the WindowEvent should implement this interface.The object of that class must be registered with a component. The object can be registered using the addWindowListener() method.

Объявление интерфейса

Following is the declaration for java.awt.event.WindowListener interface:

public interface WindowListener
   extends EventListener

Методы интерфейса

SN Метод и описание
1

void windowActivated(WindowEvent e)

Invoked when the Window is set to be the active Window.

2

void windowClosed(WindowEvent e)

Invoked when a window has been closed as the result of calling dispose on the window.

3

void windowClosing(WindowEvent e)

Invoked when the user attempts to close the window from the window’s system menu.

4

void windowDeactivated(WindowEvent e)

Invoked when a Window is no longer the active Window.

5

void windowDeiconified(WindowEvent e)

Invoked when a window is changed from a minimized to a normal state.

6

void windowIconified(WindowEvent e)

Invoked when a window is changed from a normal to a minimized state.

7

void windowOpened(WindowEvent e)

Invoked the first time a window is made visible.

void windowActivated(WindowEvent e)

Invoked when the Window is set to be the active Window.

void windowClosed(WindowEvent e)

Invoked when a window has been closed as the result of calling dispose on the window.

void windowClosing(WindowEvent e)

Invoked when the user attempts to close the window from the window’s system menu.

void windowDeactivated(WindowEvent e)

Invoked when a Window is no longer the active Window.

void windowDeiconified(WindowEvent e)

Invoked when a window is changed from a minimized to a normal state.

void windowIconified(WindowEvent e)

Invoked when a window is changed from a normal to a minimized state.

void windowOpened(WindowEvent e)

Invoked the first time a window is made visible.

Методы унаследованы

This interface inherits methods from the following interfaces:

  • java.awt.EventListener

java.awt.EventListener

WindowListener Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtListenerDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtListenerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtListenerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtListenerDemo  awtListenerDemo = new AwtListenerDemo();  
      awtListenerDemo.showWindowListenerDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
   
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showWindowListenerDemo(){
      headerLabel.setText("Listener in action: WindowListener");      

      Button okButton = new Button("OK");

      aboutFrame = new Frame();
      aboutFrame.setSize(300,200);;
      aboutFrame.setTitle("WindowListener Demo");
      aboutFrame.addWindowListener(new CustomWindowListener());

      Label msgLabel = new Label("Welcome to tutorialspoint.");
      msgLabel.setAlignment(Label.CENTER);
      msgLabel.setSize(100,100);
      aboutFrame.add(msgLabel);
      aboutFrame.setVisible(true);
   }

   class CustomWindowListener implements WindowListener {
      public void windowOpened(WindowEvent e) {
      }

      public void windowClosing(WindowEvent e) {
         aboutFrame.dispose();      
      }
      
      public void windowClosed(WindowEvent e) {
      }

      public void windowIconified(WindowEvent e) {
      }

      public void windowDeiconified(WindowEvent e) {
      }

      public void windowActivated(WindowEvent e) {
      }

      public void windowDeactivated(WindowEvent e) {
      }
   }   
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo

Проверьте следующий вывод

AWT WindowListener

AWT AdjustmentListener Interface

Вступление

The interface AdjustmentListener is used for receiving adjustment events. The class that process adjustment events needs to implements this interface.

Объявление класса

Following is the declaration for java.awt.event.AdjustmentListener interface:

public interface AdjustmentListener
extends EventListener

Методы интерфейса

SN Метод и описание
1

void adjustmentValueChanged(AdjustmentEvent e)

Invoked when the value of the adjustable has changed.

void adjustmentValueChanged(AdjustmentEvent e)

Invoked when the value of the adjustable has changed.

Методы унаследованы

This class inherits methods from the following interfaces:

  • java.awt.event.EventListener

java.awt.event.EventListener

AdjustmentListener Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtListenerDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtListenerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtListenerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtListenerDemo  awtListenerDemo = new AwtListenerDemo();  
      awtListenerDemo.showAdjustmentListenerDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
   
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showAdjustmentListenerDemo(){
      headerLabel.setText("Listener in action: AdjustmentListener");      

      ScrollPane panel = new ScrollPane();      
      panel.setBackground(Color.magenta);
      panel.getHAdjustable().addAdjustmentListener(new CustomAdjustmentListener());

      Label msglabel = new Label();
      msglabel.setAlignment(Label.CENTER);   
      msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");
      panel.add(msglabel);
      
      controlPanel.add(panel);
      mainFrame.setVisible(true);  
   }

   class CustomAdjustmentListener implements AdjustmentListener {
      public void adjustmentValueChanged(AdjustmentEvent e) {
         statusLabel.setText("Adjustment value: "+Integer.toString(e.getValue()));
      }
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo

Проверьте следующий вывод

AWT AdjustmentListener

AWT ContainerListener Interface

Вступление

The interface ContainerListener is used for receiving container events. The class that process container events needs to implements this interface.

Объявление класса

Following is the declaration for java.awt.event.ContainerListener interface:

public interface ContainerListener
extends EventListener

Методы интерфейса

SN Метод и описание
1

void componentAdded(ContainerEvent e)

Invoked when a component has been added to the container.

2

void componentRemoved(ContainerEvent e)

Invoked when a component has been removed from the container.

void componentAdded(ContainerEvent e)

Invoked when a component has been added to the container.

void componentRemoved(ContainerEvent e)

Invoked when a component has been removed from the container.

Методы унаследованы

This class inherits methods from the following interfaces:

  • java.awt.event.EventListener

java.awt.event.EventListener

AdjustmentListener Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtListenerDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtListenerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtListenerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtListenerDemo  awtListenerDemo = new AwtListenerDemo();  
      awtListenerDemo.showContainerListenerDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
   
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showContainerListenerDemo(){
      headerLabel.setText("Listener in action: ContainerListener");      

      ScrollPane panel = new ScrollPane();      
      panel.setBackground(Color.magenta);            
      panel.addContainerListener(new CustomContainerListener());  

      Label msglabel = new Label();
      msglabel.setAlignment(Label.CENTER);
      msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");
      panel.add(msglabel);
   
      controlPanel.add(panel);
      mainFrame.setVisible(true);  
   }

   class CustomContainerListener implements ContainerListener {
      public void componentAdded(ContainerEvent e) {
         statusLabel.setText(statusLabel.getText() 
         + e.getComponent().getClass().getSimpleName() + " added. ");
      }

      public void componentRemoved(ContainerEvent e) {
         statusLabel.setText(statusLabel.getText() 
         + e.getComponent().getClass().getSimpleName() + " removed. ");
      }
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo

Проверьте следующий вывод

AWT ContainerListener

AWT MouseMotionListener Interface

Вступление

The interface MouseMotionListener is used for receiving mouse motion events on a component. The class that process mouse motion events needs to implements this interface.

Объявление класса

Following is the declaration for java.awt.event.MouseMotionListener interface:

public interface MouseMotionListener
extends EventListener

Методы интерфейса

SN Метод и описание
1

void mouseDragged(MouseEvent e)

Invoked when a mouse button is pressed on a component and then dragged.

2

void mouseMoved(MouseEvent e)

Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed.

void mouseDragged(MouseEvent e)

Invoked when a mouse button is pressed on a component and then dragged.

void mouseMoved(MouseEvent e)

Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed.

Методы унаследованы

This class inherits methods from the following interfaces:

  • java.awt.event.EventListener

java.awt.event.EventListener

MouseMotionListener Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtListenerDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtListenerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtListenerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtListenerDemo  awtListenerDemo = new AwtListenerDemo();  
      awtListenerDemo.showMouseMotionListenerDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
   
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showMouseMotionListenerDemo(){
      headerLabel.setText("Listener in action: MouseMotionListener");      

      Panel panel = new Panel();      
      panel.setBackground(Color.magenta);
      panel.setLayout(new FlowLayout());        
      panel.addMouseMotionListener(new CustomMouseMotionListener());

      Label msglabel = new Label();
      msglabel.setAlignment(Label.CENTER);
      msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");
      panel.add(msglabel);

      controlPanel.add(panel);

      mainFrame.setVisible(true);  
   }   

   class CustomMouseMotionListener implements MouseMotionListener {

      public void mouseDragged(MouseEvent e) {
         statusLabel.setText("Mouse Dragged: ("+e.getX()+", "+e.getY() +")");
      }

      public void mouseMoved(MouseEvent e) {
         statusLabel.setText("Mouse Moved: ("+e.getX()+", "+e.getY() +")");
      }    
   }    
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo

Проверьте следующий вывод

AWT MouseMotionListener

AWT FocusListener Interface

Вступление

The interface FocusListener is used for receiving keyboard focus events. The class that process focus events needs to implements this interface.

Объявление класса

Following is the declaration for java.awt.event.FocusListener interface:

public interface FocusListener
extends EventListener

Методы интерфейса

SN Метод и описание
1

void focusGained(FocusEvent e)

Invoked when a component gains the keyboard focus.

2

void focusLost(FocusEvent e)

Invoked when a component loses the keyboard focus.

void focusGained(FocusEvent e)

Invoked when a component gains the keyboard focus.

void focusLost(FocusEvent e)

Invoked when a component loses the keyboard focus.

Методы унаследованы

This class inherits methods from the following interfaces:

  • java.awt.event.EventListener

java.awt.event.EventListener

FocusListener Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtListenerDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtListenerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtListenerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtListenerDemo  awtListenerDemo = new AwtListenerDemo();  
      awtListenerDemo.showFocusListenerDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
   
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

       
   private void showFocusListenerDemo(){

      headerLabel.setText("Listener in action: FocusListener");      

      Button okButton = new Button("OK");
      Button cancelButton = new Button("Cancel");
      okButton.addFocusListener(new CustomFocusListener());  
      cancelButton.addFocusListener(new CustomFocusListener());  

      controlPanel.add(okButton);
      controlPanel.add(cancelButton);     
      mainFrame.setVisible(true);  
   }

   class CustomFocusListener implements FocusListener{
      public void focusGained(FocusEvent e) {
         statusLabel.setText(statusLabel.getText() 
         + e.getComponent().getClass().getSimpleName() + " gained focus. ");
      }

      public void focusLost(FocusEvent e) {
         statusLabel.setText(statusLabel.getText() 
         + e.getComponent().getClass().getSimpleName() + " lost focus. ");
      }
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo

Проверьте следующий вывод

AWT focusListener

Адаптеры событий AWT

Адаптеры – это абстрактные классы для получения различных событий. Методы в этих классах пусты. Эти классы существуют как удобство для создания объектов слушателя.

AWT адаптеры:

Ниже приведен список часто используемых адаптеров при прослушивании событий графического интерфейса в AWT.

AWT FocusAdapter Class

Вступление

The class FocusAdapter is an abstract (adapter) class for receiving keyboard focus events. All methods of this class are empty. This class is convenience class for creating listener objects.

Объявление класса

Following is the declaration for java.awt.event.FocusAdapter class:

public abstract class FocusAdapter
   extends Object
      implements FocusListener

Конструкторы классов

SN Конструктор и описание
1

FocusAdapter()

FocusAdapter()

Методы класса

SN Метод и описание
1

void focusGained(FocusEvent e)

Invoked when a component gains the keyboard focus.

2

focusLost(FocusEvent e)

Invoked when a component loses the keyboard focus.

void focusGained(FocusEvent e)

Invoked when a component gains the keyboard focus.

focusLost(FocusEvent e)

Invoked when a component loses the keyboard focus.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.lang.Object

java.lang.Object

FocusAdapter Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtAdapterDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtAdapterDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtAdapterDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtAdapterDemo  awtAdapterDemo = new AwtAdapterDemo();        
      awtAdapterDemo.showFocusAdapterDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showFocusAdapterDemo(){

      headerLabel.setText("Listener in action: FocusAdapter");      

      Button okButton = new Button("OK");
      Button cancelButton = new Button("Cancel");
      okButton.addFocusListener(new FocusAdapter(){
         public void focusGained(FocusEvent e) {
            statusLabel.setText(statusLabel.getText() 
            + e.getComponent().getClass().getSimpleName() 
            + " gained focus. ");
         }
      });  
      
      cancelButton.addFocusListener(new FocusAdapter(){
         public void focusLost(FocusEvent e) {
            statusLabel.setText(statusLabel.getText() 
            + e.getComponent().getClass().getSimpleName() 
            + " lost focus. ");
         }
      });  
      
      controlPanel.add(okButton);
      controlPanel.add(cancelButton);     
      mainFrame.setVisible(true);  
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtAdapterDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtAdapterDemo

Проверьте следующий вывод

AWT FocusAdapter

AWT KeyAdapter Class

Вступление

The class KeyAdapter is an abstract (adapter) class for receiving keyboard events. All methods of this class are empty. This class is convenience class for creating listener objects.

Объявление класса

Following is the declaration for java.awt.event.KeyAdapter class:

public abstract class KeyAdapter
   extends Object
      implements KeyListener

Конструкторы классов

SN Конструктор и описание
1

KeyAdapter()

KeyAdapter()

Методы класса

SN Метод и описание
1

void keyPressed(KeyEvent e)

Invoked when a key has been pressed.

2

void keyReleased(KeyEvent e)

Invoked when a key has been released.

3

void keyTyped(KeyEvent e)

Invoked when a key has been typed.

void keyPressed(KeyEvent e)

Invoked when a key has been pressed.

void keyReleased(KeyEvent e)

Invoked when a key has been released.

void keyTyped(KeyEvent e)

Invoked when a key has been typed.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.lang.Object

java.lang.Object

KeyAdapter Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtAdapterDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtAdapterDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtAdapterDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtAdapterDemo  awtAdapterDemo = new AwtAdapterDemo();        
      awtAdapterDemo.showKeyAdapterDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showKeyAdapterDemo(){
      headerLabel.setText("Listener in action: KeyAdapter");      

      final TextField textField = new TextField(10);

      textField.addKeyListener(new KeyAdapter() {
         public void keyPressed(KeyEvent e) {                
            if(e.getKeyCode() == KeyEvent.VK_ENTER){
               statusLabel.setText("Entered text: " + textField.getText());
            }
         }        
      });
      Button okButton = new Button("OK");
      okButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            statusLabel.setText("Entered text: " + textField.getText());                
         }
      });

      controlPanel.add(textField);
      controlPanel.add(okButton);    
      mainFrame.setVisible(true);  
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtAdapterDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtAdapterDemo

Проверьте следующий вывод

AWT KeyAdapter

AWT MouseAdapter Class

Вступление

The class MouseAdapter is an abstract (adapter) class for receiving mouse events. All methods of this class are empty. This class is convenience class for creating listener objects.

Объявление класса

Following is the declaration for java.awt.event.MouseAdapter class:

public abstract class MouseAdapter
   extends Object
      implements MouseListener, MouseWheelListener, MouseMotionListener

Конструкторы классов

SN Конструктор и описание
1

MouseAdapter()

MouseAdapter()

Методы класса

SN Метод и описание
1

void mouseClicked(MouseEvent e)

Invoked when the mouse button has been clicked (pressed and released) on a component.

2

void mouseDragged(MouseEvent e)

Invoked when a mouse button is pressed on a component and then dragged.

3

void mouseEntered(MouseEvent e)

Invoked when the mouse enters a component.

4

void mouseExited(MouseEvent e)

Invoked when the mouse exits a component.

5

void mouseMoved(MouseEvent e)

Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed.

6

void mousePressed(MouseEvent e)

Invoked when a mouse button has been pressed on a component.

7

void mouseReleased(MouseEvent e)

Invoked when a mouse button has been released on a component.

8

void mouseWheelMoved(MouseWheelEvent e)

Invoked when the mouse wheel is rotated.

void mouseClicked(MouseEvent e)

Invoked when the mouse button has been clicked (pressed and released) on a component.

void mouseDragged(MouseEvent e)

Invoked when a mouse button is pressed on a component and then dragged.

void mouseEntered(MouseEvent e)

Invoked when the mouse enters a component.

void mouseExited(MouseEvent e)

Invoked when the mouse exits a component.

void mouseMoved(MouseEvent e)

Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed.

void mousePressed(MouseEvent e)

Invoked when a mouse button has been pressed on a component.

void mouseReleased(MouseEvent e)

Invoked when a mouse button has been released on a component.

void mouseWheelMoved(MouseWheelEvent e)

Invoked when the mouse wheel is rotated.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.lang.Object

java.lang.Object

MouseAdapter Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtAdapterDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtAdapterDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtAdapterDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtAdapterDemo  awtAdapterDemo = new AwtAdapterDemo();  
      awtAdapterDemo.showMouseAdapterDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showMouseAdapterDemo(){
      headerLabel.setText("Listener in action: MouseAdapter");      

      Panel panel = new Panel();      
      panel.setBackground(Color.magenta);
      panel.setLayout(new FlowLayout());        
      panel.addMouseListener(new MouseAdapter(){
         public void mouseClicked(MouseEvent e) {
            statusLabel.setText("Mouse Clicked: ("
            +e.getX()+", "+e.getY() +")");
         }                
      });

      Label msglabel = new Label();
      msglabel.setAlignment(Label.CENTER);
      msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");

      msglabel.addMouseListener(new MouseAdapter(){
         public void mouseClicked(MouseEvent e) {
            statusLabel.setText("Mouse Clicked: ("
            +e.getX()+", "+e.getY() +")");
         }                
      });
      panel.add(msglabel);
      controlPanel.add(panel);
      mainFrame.setVisible(true);  
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtAdapterDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtAdapterDemo

Проверьте следующий вывод

AWT MouseAdapter

AWT MouseMotionAdapter Class

Вступление

The class MouseMotionAdapter is an abstract (adapter) class for receiving mouse motion events. All methods of this class are empty. This class is convenience class for creating listener objects.

Объявление класса

Following is the declaration for java.awt.event.MouseMotionAdapter class:

public abstract class MouseMotionAdapter
   extends Object
      implements MouseMotionListener

Конструкторы классов

SN Конструктор и описание
1

MouseMotionAdapter()

MouseMotionAdapter()

Методы класса

SN Метод и описание
1

void mouseDragged(MouseEvent e)

Invoked when a mouse button is pressed on a component and then dragged.

2

void mouseMoved(MouseEvent e)

Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed.

void mouseDragged(MouseEvent e)

Invoked when a mouse button is pressed on a component and then dragged.

void mouseMoved(MouseEvent e)

Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.lang.Object

java.lang.Object

MouseMotionAdapter Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtAdapterDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtAdapterDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtAdapterDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtAdapterDemo  awtAdapterDemo = new AwtAdapterDemo();        
      awtAdapterDemo.showMouseMotionAdapterDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showMouseMotionAdapterDemo(){
      headerLabel.setText("Listener in action: MouseMotionAdapter");      

      Panel panel = new Panel();      
      panel.setBackground(Color.magenta);
      panel.setLayout(new FlowLayout());        
      panel.addMouseMotionListener(new MouseMotionAdapter(){
         public void mouseMoved(MouseEvent e) {
            statusLabel.setText("Mouse Moved: ("+e.getX()+", "+e.getY() +")");
         }                
      });

      Label msglabel = new Label();
      msglabel.setAlignment(Label.CENTER);
      msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");
      panel.add(msglabel);

      controlPanel.add(panel);

      mainFrame.setVisible(true);  
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtAdapterDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtAdapterDemo

Проверьте следующий вывод

AWT MouseMotionAdapter

AWT WindowAdapter Class

Вступление

The class WindowAdapter is an abstract (adapter) class for receiving window events. All methods of this class are empty. This class is convenience class for creating listener objects.

Объявление класса

Following is the declaration for java.awt.event.WindowAdapter class:

public abstract class WindowAdapter
   extends Object
      implements WindowListener, WindowStateListener, WindowFocusListener

Конструкторы классов

SN Конструктор и описание
1

WindowAdapter()

WindowAdapter()

Методы класса

SN Метод и описание
1

void windowActivated(WindowEvent e)

Invoked when a window is activated.

2

void windowClosed(WindowEvent e)

Invoked when a window has been closed.

3

void windowClosing(WindowEvent e)

Invoked when a window is in the process of being closed.

4

void windowDeactivated(WindowEvent e)

Invoked when a window is de-activated.

5

void windowDeiconified(WindowEvent e)

Invoked when a window is de-iconified.

6

void windowGainedFocus(WindowEvent e)

Invoked when the Window is set to be the focused Window, which means that the Window, or one of its subcomponents, will receive keyboard events.

7

void windowIconified(WindowEvent e)

Invoked when a window is iconified.

8

void windowLostFocus(WindowEvent e)

Invoked when the Window is no longer the focused Window, which means that keyboard events will no longer be delivered to the Window or any of its subcomponents.

9

void windowOpened(WindowEvent e)

Invoked when a window has been opened.

10

void windowStateChanged(WindowEvent e)

Invoked when a window state is changed.

void windowActivated(WindowEvent e)

Invoked when a window is activated.

void windowClosed(WindowEvent e)

Invoked when a window has been closed.

void windowClosing(WindowEvent e)

Invoked when a window is in the process of being closed.

void windowDeactivated(WindowEvent e)

Invoked when a window is de-activated.

void windowDeiconified(WindowEvent e)

Invoked when a window is de-iconified.

void windowGainedFocus(WindowEvent e)

Invoked when the Window is set to be the focused Window, which means that the Window, or one of its subcomponents, will receive keyboard events.

void windowIconified(WindowEvent e)

Invoked when a window is iconified.

void windowLostFocus(WindowEvent e)

Invoked when the Window is no longer the focused Window, which means that keyboard events will no longer be delivered to the Window or any of its subcomponents.

void windowOpened(WindowEvent e)

Invoked when a window has been opened.

void windowStateChanged(WindowEvent e)

Invoked when a window state is changed.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.lang.Object

java.lang.Object

WindowAdapter Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtAdapterDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtAdapterDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtAdapterDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtAdapterDemo  awtAdapterDemo = new AwtAdapterDemo();        
      awtAdapterDemo.showWindowAdapterDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showWindowAdapterDemo(){
      headerLabel.setText("Listener in action: WindowAdapter");      

      Button okButton = new Button("OK");

      final Frame aboutFrame = new Frame();
      aboutFrame.setSize(300,200);;
      aboutFrame.setTitle("WindowAdapter Demo");
      aboutFrame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent windowEvent){
               aboutFrame.dispose();
         }        
      });    
      Label msgLabel = new Label("Welcome to tutorialspoint.");
      msgLabel.setAlignment(Label.CENTER);
      msgLabel.setSize(100,100);
      aboutFrame.add(msgLabel);
      aboutFrame.setVisible(true);
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtAdapterDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtAdapterDemo

Проверьте следующий вывод

AWT WindowAdapter

Макеты AWT

Вступление

Расположение означает расположение компонентов внутри контейнера. По-другому можно сказать, что размещение компонентов в определенной позиции внутри контейнера. Задача размещения элементов управления выполняется автоматически менеджером макетов.

Менеджер по расположению

Менеджер по расположению автоматически размещает все компоненты в контейнере. Если мы не используем менеджер компоновки, то компоненты также размещаются менеджером компоновки по умолчанию. Можно расположить элементы управления вручную, но это становится очень трудным из-за следующих двух причин.

  • Очень утомительно обрабатывать большое количество элементов управления внутри контейнера.

  • Часто информация о ширине и высоте компонента не предоставляется, когда нам нужно их упорядочить.

Очень утомительно обрабатывать большое количество элементов управления внутри контейнера.

Часто информация о ширине и высоте компонента не предоставляется, когда нам нужно их упорядочить.

Java предоставляет нам различные диспетчера размещения для размещения элементов управления. Свойства, такие как размер, форма и расположение, варьируются от одного менеджера макета к другому менеджеру макета. Когда размер апплета или окна приложения изменяет размер, форма и расположение компонентов также изменяются в ответ, то есть менеджеры компоновки адаптируются к размерам окна просмотра апплета или окна приложения.

Диспетчер компоновки связан с каждым объектом-контейнером. Каждый менеджер компоновки является объектом класса, который реализует интерфейс LayoutManager.

Following are the interfaces and classes defining functionalities of Layout Managers.

AWT LayoutManager Interface

Вступление

The interface LayoutManager is used to define the interface for classes that know how to lay out Containers.

Объявление класса

Following is the declaration for java.awt.LayoutManager interface:

public interface LayoutManager

Методы интерфейса

SN Метод и описание
1

void addLayoutComponent(String name, Component comp)

If the layout manager uses a per-component string, adds the component comp to the layout, associating it with the string specified by name.

2

void layoutContainer(Container parent)

Lays out the specified container.

3

Dimension minimumLayoutSize(Container parent)

Calculates the minimum size dimensions for the specified container, given the components it contains.

4

Dimension preferredLayoutSize(Container parent)

Calculates the preferred size dimensions for the specified container, given the components it contains.

5

void removeLayoutComponent(Component comp)

Removes the specified component from the layout.

void addLayoutComponent(String name, Component comp)

If the layout manager uses a per-component string, adds the component comp to the layout, associating it with the string specified by name.

void layoutContainer(Container parent)

Lays out the specified container.

Dimension minimumLayoutSize(Container parent)

Calculates the minimum size dimensions for the specified container, given the components it contains.

Dimension preferredLayoutSize(Container parent)

Calculates the preferred size dimensions for the specified container, given the components it contains.

void removeLayoutComponent(Component comp)

Removes the specified component from the layout.

AWT LayoutManager2 Interface

Вступление

The interface LayoutManger is used to define the interface for classes that know how to lay out Containers based on a layout constraints object.

Объявление класса

Following is the declaration for java.awt.LayoutManager2 interface:

public interface LayoutManger2
   extends LayoutManager

Методы интерфейса

SN Метод и описание
1

void addLayoutComponent(Component comp, Object constraints)

Adds the specified component to the layout, using the specified constraint object.

2

float getLayoutAlignmentX(Container target)

Returns the alignment along the x axis.

3

float getLayoutAlignmentY(Container target)

Returns the alignment along the y axis.

4

void invalidateLayout(Container target)

Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.

5

Dimension maximumLayoutSize(Container target)

Calculates the maximum size dimensions for the specified container, given the components it contains.

void addLayoutComponent(Component comp, Object constraints)

Adds the specified component to the layout, using the specified constraint object.

float getLayoutAlignmentX(Container target)

Returns the alignment along the x axis.

float getLayoutAlignmentY(Container target)

Returns the alignment along the y axis.

void invalidateLayout(Container target)

Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.

Dimension maximumLayoutSize(Container target)

Calculates the maximum size dimensions for the specified container, given the components it contains.

AWT BorderLayout Class

Вступление

The class BorderLayout arranges the components to fit in the five regions: east, west, north, south and center. Each region is can contain only one component and each component in each region is identified by the corresponding constant NORTH, SOUTH, EAST, WEST, and CENTER.

Объявление класса

Following is the declaration for java.awt.BorderLayout class:

public class BorderLayout
   extends Object
      implements LayoutManager2, Serializable

поле

Following are the fields for java.awt.BorderLayout class:

  • static String AFTER_LAST_LINE — Synonym for PAGE_END.

  • static String AFTER_LINE_ENDS — Synonym for LINE_END.

  • static String BEFORE_FIRST_LINE — Synonym for PAGE_START.

  • static String BEFORE_LINE_BEGINS — Synonym for LINE_START.

  • static String CENTER — The center layout constraint (middle of container).

  • static String EAST — The east layout constraint (right side of container).

  • static String LINE_END — The component goes at the end of the line direction for the layout.

  • static String LINE_START — The component goes at the beginning of the line direction for the layout.

  • static String NORTH — The north layout constraint (top of container).

  • static String PAGE_END — The component comes after the last line of the layout’s content.

  • static String PAGE_START — The component comes before the first line of the layout’s content.

  • static String SOUTH — The south layout constraint (bottom of container).

  • static String WEST — The west layout constraint (left side of container).

static String AFTER_LAST_LINE — Synonym for PAGE_END.

static String AFTER_LINE_ENDS — Synonym for LINE_END.

static String BEFORE_FIRST_LINE — Synonym for PAGE_START.

static String BEFORE_LINE_BEGINS — Synonym for LINE_START.

static String CENTER — The center layout constraint (middle of container).

static String EAST — The east layout constraint (right side of container).

static String LINE_END — The component goes at the end of the line direction for the layout.

static String LINE_START — The component goes at the beginning of the line direction for the layout.

static String NORTH — The north layout constraint (top of container).

static String PAGE_END — The component comes after the last line of the layout’s content.

static String PAGE_START — The component comes before the first line of the layout’s content.

static String SOUTH — The south layout constraint (bottom of container).

static String WEST — The west layout constraint (left side of container).

Конструкторы классов

SN Конструктор и описание
1

BorderLayout()

Constructs a new border layout with no gaps between components.

2

BorderLayout(int hgap, int vgap)

Constructs a border layout with the specified gaps between components.

BorderLayout()

Constructs a new border layout with no gaps between components.

BorderLayout(int hgap, int vgap)

Constructs a border layout with the specified gaps between components.

Методы класса

SN Метод и описание
1

void addLayoutComponent(Component comp, Object constraints)

Adds the specified component to the layout, using the specified constraint object.

2

void addLayoutComponent(String name, Component comp)

If the layout manager uses a per-component string, adds the component comp to the layout, associating it with the string specified by name.

3

int getHgap()

Returns the horizontal gap between components.

4

float getLayoutAlignmentX(Container parent)

Returns the alignment along the x axis.

5

float getLayoutAlignmentY(Container parent)

Returns the alignment along the y axis.

6

int getVgap()

Returns the vertical gap between components.

7

void invalidateLayout(Container target)

Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.

8

void layoutContainer(Container target)


9

Dimension maximumLayoutSize(Container target)

Returns the maximum dimensions for this layout given the components in the specified target container.

10

Dimension minimumLayoutSize(Container target)

Determines the minimum size of the target container using this layout manager.

11

Dimension preferredLayoutSize(Container target)

Determines the preferred size of the target container using this layout manager, based on the components in the container.

12

void removeLayoutComponent(Component comp)

Removes the specified component from this border layout.

13

void setHgap(int hgap)

Sets the horizontal gap between components.

14

void setVgap(int vgap)

Sets the vertical gap between components.

15

Строка toString ()

Returns a string representation of the state of this border layout.

void addLayoutComponent(Component comp, Object constraints)

Adds the specified component to the layout, using the specified constraint object.

void addLayoutComponent(String name, Component comp)

If the layout manager uses a per-component string, adds the component comp to the layout, associating it with the string specified by name.

int getHgap()

Returns the horizontal gap between components.

float getLayoutAlignmentX(Container parent)

Returns the alignment along the x axis.

float getLayoutAlignmentY(Container parent)

Returns the alignment along the y axis.

int getVgap()

Returns the vertical gap between components.

void invalidateLayout(Container target)

Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.

void layoutContainer(Container target)

Dimension maximumLayoutSize(Container target)

Returns the maximum dimensions for this layout given the components in the specified target container.

Dimension minimumLayoutSize(Container target)

Determines the minimum size of the target container using this layout manager.

Dimension preferredLayoutSize(Container target)

Determines the preferred size of the target container using this layout manager, based on the components in the container.

void removeLayoutComponent(Component comp)

Removes the specified component from this border layout.

void setHgap(int hgap)

Sets the horizontal gap between components.

void setVgap(int vgap)

Sets the vertical gap between components.

Строка toString ()

Returns a string representation of the state of this border layout.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.lang.Object

java.lang.Object

BorderLayout Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtLayoutDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtLayoutDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;
   private Label msglabel;

   public AwtLayoutDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtLayoutDemo  awtLayoutDemo = new AwtLayoutDemo();  
      awtLayoutDemo.showBorderLayoutDemo();       
   }
      
   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      msglabel = new Label();
      msglabel.setAlignment(Label.CENTER);
      msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showBorderLayoutDemo(){
      headerLabel.setText("Layout in action: BorderLayout");      

      Panel panel = new Panel();
      panel.setBackground(Color.darkGray);
      panel.setSize(300,300);
      BorderLayout layout = new BorderLayout();
      layout.setHgap(10);
      layout.setVgap(10);
      panel.setLayout(layout);        
	  
      panel.add(new Button("Center"),BorderLayout.CENTER);
      panel.add(new Button("Line Start"),BorderLayout.LINE_START); 
      panel.add(new Button("Line End"),BorderLayout.LINE_END);
      panel.add(new Button("East"),BorderLayout.EAST);   
      panel.add(new Button("West"),BorderLayout.WEST); 
      panel.add(new Button("North"),BorderLayout.NORTH); 
      panel.add(new Button("South"),BorderLayout.SOUTH); 

      controlPanel.add(panel);

      mainFrame.setVisible(true);  
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtlayoutDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtlayoutDemo

Проверьте следующий вывод

AWT BorderLayout

AWT CardLayout Class

Вступление

The class CardLayout arranges each component in the container as a card. Only one card is visible at a time, and the container acts as a stack of cards.

Объявление класса

Following is the declaration for java.awt.CardLayout class:

public class CardLayout
   extends Object
      implements LayoutManager2, Serializable

Конструкторы классов

SN Конструктор и описание
1

CardLayout()

Creates a new card layout with gaps of size zero.

2

CardLayout(int hgap, int vgap)

Creates a new card layout with the specified horizontal and vertical gaps.

CardLayout()

Creates a new card layout with gaps of size zero.

CardLayout(int hgap, int vgap)

Creates a new card layout with the specified horizontal and vertical gaps.

Методы класса

SN Метод и описание
1

void addLayoutComponent(Component comp, Object constraints)

Adds the specified component to this card layout’s internal table of names.

2

void addLayoutComponent(String name, Component comp)

If the layout manager uses a per-component string, adds the component comp to the layout, associating it with the string specified by name.

3

void first(Container parent)

Flips to the first card of the container.

4

int getHgap()

Gets the horizontal gap between components.

5

float getLayoutAlignmentX(Container parent)

Returns the alignment along the x axis.

6

float getLayoutAlignmentY(Container parent)

Returns the alignment along the y axis.

7

int getVgap()

Gets the vertical gap between components.

8

void invalidateLayout(Container target)

Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.

9

void last(Container parent)

Flips to the last card of the container.

10

void layoutContainer(Container parent)

Lays out the specified container using this card layout.

11

Dimension maximumLayoutSize(Container target)

Returns the maximum dimensions for this layout given the components in the specified target container.

12

Dimension minimumLayoutSize(Container parent)

Calculates the minimum size for the specified panel.

13

void next(Container parent)

Flips to the next card of the specified container.

14

Dimension preferredLayoutSize(Container parent)

Determines the preferred size of the container argument using this card layout.

15

void previous(Container parent)

Flips to the previous card of the specified container.

16

void removeLayoutComponent(Component comp)

Removes the specified component from the layout.

17

void setHgap(int hgap)

Sets the horizontal gap between components.

18

void setVgap(int vgap)

Sets the vertical gap between components.

19

void show(Container parent, String name)

Flips to the component that was added to this layout with the specified name, using addLayoutComponent.

20

Строка toString ()

Returns a string representation of the state of this card layout.

void addLayoutComponent(Component comp, Object constraints)

Adds the specified component to this card layout’s internal table of names.

void addLayoutComponent(String name, Component comp)

If the layout manager uses a per-component string, adds the component comp to the layout, associating it with the string specified by name.

void first(Container parent)

Flips to the first card of the container.

int getHgap()

Gets the horizontal gap between components.

float getLayoutAlignmentX(Container parent)

Returns the alignment along the x axis.

float getLayoutAlignmentY(Container parent)

Returns the alignment along the y axis.

int getVgap()

Gets the vertical gap between components.

void invalidateLayout(Container target)

Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.

void last(Container parent)

Flips to the last card of the container.

void layoutContainer(Container parent)

Lays out the specified container using this card layout.

Dimension maximumLayoutSize(Container target)

Returns the maximum dimensions for this layout given the components in the specified target container.

Dimension minimumLayoutSize(Container parent)

Calculates the minimum size for the specified panel.

void next(Container parent)

Flips to the next card of the specified container.

Dimension preferredLayoutSize(Container parent)

Determines the preferred size of the container argument using this card layout.

void previous(Container parent)

Flips to the previous card of the specified container.

void removeLayoutComponent(Component comp)

Removes the specified component from the layout.

void setHgap(int hgap)

Sets the horizontal gap between components.

void setVgap(int vgap)

Sets the vertical gap between components.

void show(Container parent, String name)

Flips to the component that was added to this layout with the specified name, using addLayoutComponent.

Строка toString ()

Returns a string representation of the state of this card layout.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.lang.Object

java.lang.Object

CardLayout Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtLayoutDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtLayoutDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;
   private Label msglabel;

   public AwtLayoutDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtLayoutDemo  awtLayoutDemo = new AwtLayoutDemo();  
      awtLayoutDemo.showCardLayoutDemo();       
   }
      
   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      msglabel = new Label();
      msglabel.setAlignment(Label.CENTER);
      msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showCardLayoutDemo(){
      headerLabel.setText("Layout in action: CardLayout");      

      final Panel panel = new Panel();
      panel.setBackground(Color.CYAN);
      panel.setSize(300,300);

      CardLayout layout = new CardLayout();
      layout.setHgap(10);
      layout.setVgap(10);
      panel.setLayout(layout);        

      Panel buttonPanel = new Panel(new FlowLayout());

      buttonPanel.add(new Button("OK"));
      buttonPanel.add(new Button("Cancel"));    

      Panel textBoxPanel = new Panel(new FlowLayout());

      textBoxPanel.add(new Label("Name:"));
      textBoxPanel.add(new TextField(20));

      panel.add("Button", buttonPanel);
      panel.add("Text", textBoxPanel);

      Choice choice = new Choice();
      choice.add("Button");
      choice.add("Text");

      choice.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            CardLayout cardLayout = (CardLayout)(panel.getLayout());
            cardLayout.show(panel, (String)e.getItem());
         }
      });
      controlPanel.add(choice);
      controlPanel.add(panel);

      mainFrame.setVisible(true);  
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtlayoutDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtlayoutDemo

Проверьте следующий вывод

AWT CardLayout

AWT FlowLayout Class

Вступление

The class FlowLayout components in a left-to-right flow.

Объявление класса

Following is the declaration for java.awt.FlowLayout class:

public class FlowLayout
   extends Object
      implements LayoutManager, Serializable

поле

Following are the fields for java.awt.BorderLayout class:

  • static int CENTER — This value indicates that each row of components should be centered.

  • static int LEADING — This value indicates that each row of components should be justified to the leading edge of the container’s orientation, for example, to the left in left-to-right orientations.

  • static int LEFT — This value indicates that each row of components should be left-justified.

  • static int RIGHT — This value indicates that each row of components should be right-justified.

  • static int TRAILING — This value indicates that each row of components should be justified to the trailing edge of the container’s orientation, for example, to the right in left-to-right orientations.

static int CENTER — This value indicates that each row of components should be centered.

static int LEADING — This value indicates that each row of components should be justified to the leading edge of the container’s orientation, for example, to the left in left-to-right orientations.

static int LEFT — This value indicates that each row of components should be left-justified.

static int RIGHT — This value indicates that each row of components should be right-justified.

static int TRAILING — This value indicates that each row of components should be justified to the trailing edge of the container’s orientation, for example, to the right in left-to-right orientations.

Конструкторы классов

SN Конструктор и описание
1

FlowLayout()

Constructs a new FlowLayout with a centered alignment and a default 5-unit horizontal and vertical gap.

2

FlowLayout(int align)

Constructs a new FlowLayout with the specified alignment and a default 5-unit horizontal and vertical gap.

3

FlowLayout(int align, int hgap, int vgap)

Creates a new flow layout manager with the indicated alignment and the indicated horizontal and vertical gaps.

FlowLayout()

Constructs a new FlowLayout with a centered alignment and a default 5-unit horizontal and vertical gap.

FlowLayout(int align)

Constructs a new FlowLayout with the specified alignment and a default 5-unit horizontal and vertical gap.

FlowLayout(int align, int hgap, int vgap)

Creates a new flow layout manager with the indicated alignment and the indicated horizontal and vertical gaps.

Методы класса

SN Метод и описание
1

void addLayoutComponent(String name, Component comp)

Adds the specified component to the layout.

2

int getAlignment()

Gets the alignment for this layout.

3

int getHgap()

Gets the horizontal gap between components.

4

int getVgap()

Gets the vertical gap between components.

5

void layoutContainer(Container target)

Lays out the container.

6

Dimension minimumLayoutSize(Container target)

Returns the minimum dimensions needed to layout the visible components contained in the specified target container.

7

Dimension preferredLayoutSize(Container target)

Returns the preferred dimensions for this layout given the visible components in the specified target container.

8

void removeLayoutComponent(Component comp)

Removes the specified component from the layout.

9

void setAlignment(int align)

Sets the alignment for this layout.

10

void setHgap(int hgap)

Sets the horizontal gap between components.

11

void setVgap(int vgap)

Sets the vertical gap between components.

12

Строка toString ()

Returns a string representation of this FlowLayout object and its values.

void addLayoutComponent(String name, Component comp)

Adds the specified component to the layout.

int getAlignment()

Gets the alignment for this layout.

int getHgap()

Gets the horizontal gap between components.

int getVgap()

Gets the vertical gap between components.

void layoutContainer(Container target)

Lays out the container.

Dimension minimumLayoutSize(Container target)

Returns the minimum dimensions needed to layout the visible components contained in the specified target container.

Dimension preferredLayoutSize(Container target)

Returns the preferred dimensions for this layout given the visible components in the specified target container.

void removeLayoutComponent(Component comp)

Removes the specified component from the layout.

void setAlignment(int align)

Sets the alignment for this layout.

void setHgap(int hgap)

Sets the horizontal gap between components.

void setVgap(int vgap)

Sets the vertical gap between components.

Строка toString ()

Returns a string representation of this FlowLayout object and its values.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.lang.Object

java.lang.Object

FlowLayout Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtLayoutDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtLayoutDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;
   private Label msglabel;

   public AwtLayoutDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtLayoutDemo  awtLayoutDemo = new AwtLayoutDemo();  
      awtLayoutDemo.showFlowLayoutDemo();       
   }
      
   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      msglabel = new Label();
      msglabel.setAlignment(Label.CENTER);
      msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showFlowLayoutDemo(){
      headerLabel.setText("Layout in action: FlowLayout");      

      Panel panel = new Panel();
      panel.setBackground(Color.darkGray);
      panel.setSize(200,200);
      FlowLayout layout = new FlowLayout();
      layout.setHgap(10);              
      layout.setVgap(10);
      panel.setLayout(layout);        
      panel.add(new Button("OK"));
      panel.add(new Button("Cancel"));       

      controlPanel.add(panel);

      mainFrame.setVisible(true);  
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtlayoutDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtlayoutDemo

Проверьте следующий вывод

AWT FlowLayout

AWT GridLayout Class

Вступление

The class GridLayout arranges components in a rectangular grid.

Объявление класса

Following is the declaration for java.awt.GridLayout class:

public class GridLayout
   extends Object
      implements LayoutManager, Serializable

Конструкторы классов

SN Конструктор и описание
1

GridLayout()

Creates a grid layout with a default of one column per component, in a single row.

2

GridLayout(int rows, int cols)

Creates a grid layout with the specified number of rows and columns.

3

GridLayout(int rows, int cols, int hgap, int vgap)

Creates a grid layout with the specified number of rows and columns.

GridLayout()

Creates a grid layout with a default of one column per component, in a single row.

GridLayout(int rows, int cols)

Creates a grid layout with the specified number of rows and columns.

GridLayout(int rows, int cols, int hgap, int vgap)

Creates a grid layout with the specified number of rows and columns.

Методы класса

SN Метод и описание
1

void addLayoutComponent(String name, Component comp)

Adds the specified component with the specified name to the layout.

2

int getColumns()

Gets the number of columns in this layout.

3

int getHgap()

Gets the horizontal gap between components.

4

int getRows()

Gets the number of rows in this layout.

5

int getVgap()

Gets the vertical gap between components.

6

void layoutContainer(Container parent)

Lays out the specified container using this layout.

7

Dimension minimumLayoutSize(Container parent)

Determines the minimum size of the container argument using this grid layout.

8

Dimension preferredLayoutSize(Container parent)

Determines the preferred size of the container argument using this grid layout.

9

void removeLayoutComponent(Component comp)

Removes the specified component from the layout.

10

void setColumns(int cols)

Sets the number of columns in this layout to the specified value.

11

void setHgap(int hgap)

Sets the horizontal gap between components to the specified value.

12

void setRows(int rows)

Sets the number of rows in this layout to the specified value.

13

void setVgap(int vgap)

Sets the vertical gap between components to the specified value.

14

Строка toString ()

Returns the string representation of this grid layout’s values.

void addLayoutComponent(String name, Component comp)

Adds the specified component with the specified name to the layout.

int getColumns()

Gets the number of columns in this layout.

int getHgap()

Gets the horizontal gap between components.

int getRows()

Gets the number of rows in this layout.

int getVgap()

Gets the vertical gap between components.

void layoutContainer(Container parent)

Lays out the specified container using this layout.

Dimension minimumLayoutSize(Container parent)

Determines the minimum size of the container argument using this grid layout.

Dimension preferredLayoutSize(Container parent)

Determines the preferred size of the container argument using this grid layout.

void removeLayoutComponent(Component comp)

Removes the specified component from the layout.

void setColumns(int cols)

Sets the number of columns in this layout to the specified value.

void setHgap(int hgap)

Sets the horizontal gap between components to the specified value.

void setRows(int rows)

Sets the number of rows in this layout to the specified value.

void setVgap(int vgap)

Sets the vertical gap between components to the specified value.

Строка toString ()

Returns the string representation of this grid layout’s values.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.lang.Object

java.lang.Object

GridLayout Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtLayoutDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtLayoutDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;
   private Label msglabel;

   public AwtLayoutDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtLayoutDemo  awtLayoutDemo = new AwtLayoutDemo();  
      awtLayoutDemo.showGridLayoutDemo();       
   }
      
   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      msglabel = new Label();
      msglabel.setAlignment(Label.CENTER);
      msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showGridLayoutDemo(){
      headerLabel.setText("Layout in action: GridLayout");      

      Panel panel = new Panel();
      panel.setBackground(Color.darkGray);
      panel.setSize(300,300);
      GridLayout layout = new GridLayout(0,3);
      layout.setHgap(10);
      layout.setVgap(10);
      
      panel.setLayout(layout);        
      panel.add(new Button("Button 1"));
      panel.add(new Button("Button 2")); 
      panel.add(new Button("Button 3")); 
      panel.add(new Button("Button 4")); 
      panel.add(new Button("Button 5")); 
      controlPanel.add(panel);
      mainFrame.setVisible(true);  
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtlayoutDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtlayoutDemo

Проверьте следующий вывод

AWT GridLayout

AWT GridBagLayout Class

Вступление

The class GridBagLayout arranges components in a horizontal and vertical manner.

Объявление класса

Following is the declaration for java.awt.GridBagLayout class:

public class GridBagLayout
   extends Object
      implements LayoutManager2, Serializable

поле

Following are the fields for java.awt.BorderLayout class:

  • double[] columnWeights — This field holds the overrides to the column weights.

  • int[] columnWidths — This field holds the overrides to the column minimum width.

  • protected Hashtable comptable — This hashtable maintains the association between a component and its gridbag constraints.

  • protected GridBagConstraints defaultConstraints — This field holds a gridbag constraints instance containing the default values, so if a component does not have gridbag constraints associated with it, then the component will be assigned a copy of the defaultConstraints.

  • protected java.awt.GridBagLayoutInfo layoutInfo — This field holds the layout information for the gridbag.

  • protected static int MAXGRIDSIZE — The maximum number of grid positions (both horizontally and vertically) that can be laid out by the grid bag layout.

  • protected static int MINSIZE — The smallest grid that can be laid out by the grid bag layout.

  • protected static int PREFERREDSIZE — The preferred grid size that can be laid out by the grid bag layout.

  • int[] rowHeights — This field holds the overrides to the row minimum heights.

  • double[] rowWeights — This field holds the overrides to the row weights.

double[] columnWeights — This field holds the overrides to the column weights.

int[] columnWidths — This field holds the overrides to the column minimum width.

protected Hashtable comptable — This hashtable maintains the association between a component and its gridbag constraints.

protected GridBagConstraints defaultConstraints — This field holds a gridbag constraints instance containing the default values, so if a component does not have gridbag constraints associated with it, then the component will be assigned a copy of the defaultConstraints.

protected java.awt.GridBagLayoutInfo layoutInfo — This field holds the layout information for the gridbag.

protected static int MAXGRIDSIZE — The maximum number of grid positions (both horizontally and vertically) that can be laid out by the grid bag layout.

protected static int MINSIZE — The smallest grid that can be laid out by the grid bag layout.

protected static int PREFERREDSIZE — The preferred grid size that can be laid out by the grid bag layout.

int[] rowHeights — This field holds the overrides to the row minimum heights.

double[] rowWeights — This field holds the overrides to the row weights.

Конструкторы классов

SN Конструктор и описание
1

GridBagLayout()

Creates a grid bag layout manager.

GridBagLayout()

Creates a grid bag layout manager.

Методы класса

SN Метод и описание
1

void addLayoutComponent(Component comp, Object constraints)

Adds the specified component to the layout, using the specified constraints object.

2

void addLayoutComponent(String name, Component comp)

Adds the specified component with the specified name to the layout.

3

protected void adjustForGravity(GridBagConstraints constraints, Rectangle r)

Adjusts the x, y, width, and height fields to the correct values depending on the constraint geometry and pads.

4

protected void AdjustForGravity(GridBagConstraints constraints, Rectangle r)

This method is obsolete and supplied for backwards compatability only; new code should call adjustForGravity instead.

5

protected void arrangeGrid(Container parent)

Lays out the grid.

6

protected void ArrangeGrid(Container parent)

This method is obsolete and supplied for backwards compatability only; new code should call arrangeGrid instead.

7

GridBagConstraints getConstraints(Component comp)

Gets the constraints for the specified component.

8

float getLayoutAlignmentX(Container parent)

Returns the alignment along the x axis.

9

float getLayoutAlignmentY(Container parent)

Returns the alignment along the y axis.

10

int[][] getLayoutDimensions()

Determines column widths and row heights for the layout grid.

11

protected java.awt.GridBagLayoutInfo getLayoutInfo(Container parent, int sizeflag)

Fills in an instance of GridBagLayoutInfo for the current set of managed children.

12

protected java.awt.GridBagLayoutInfo GetLayoutInfo(Container parent, int sizeflag)

This method is obsolete and supplied for backwards compatability only; new code should call getLayoutInfo instead.

13

Point getLayoutOrigin()

Determines the origin of the layout area, in the graphics coordinate space of the target container.

14

double[][] getLayoutWeights()

Determines the weights of the layout grid’s columns and rows.

15

protected Dimension getMinSize(Container parent, java.awt.GridBagLayoutInfo info)

Figures out the minimum size of the master based on the information from getLayoutInfo().

16

protected Dimension GetMinSize(Container parent, java.awt.GridBagLayoutInfo info)

This method is obsolete and supplied for backwards compatability only; new code should call getMinSize instead.

17

void invalidateLayout(Container target)

Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.

18

void layoutContainer(Container parent)

Lays out the specified container using this grid bag layout.

19

Point location(int x, int y)

Determines which cell in the layout grid contains the point specified by (x, y).

20

protected GridBagConstraints lookupConstraints(Component comp)

Retrieves the constraints for the specified component.

21

Dimension maximumLayoutSize(Container target)

Returns the maximum dimensions for this layout given the components in the specified target container.

22

Dimension minimumLayoutSize(Container parent)

Determines the minimum size of the parent container using this grid bag layout.

23

Dimension preferredLayoutSize(Container parent)

Determines the preferred size of the parent container using this grid bag layout.

24

void removeLayoutComponent(Component comp)

Removes the specified component from this layout.

25

void setConstraints(Component comp, GridBagConstraints constraints)

Sets the constraints for the specified component in this layout.

26

Строка toString ()

Returns a string representation of this grid bag layout’s values.

void addLayoutComponent(Component comp, Object constraints)

Adds the specified component to the layout, using the specified constraints object.

void addLayoutComponent(String name, Component comp)

Adds the specified component with the specified name to the layout.

protected void adjustForGravity(GridBagConstraints constraints, Rectangle r)

Adjusts the x, y, width, and height fields to the correct values depending on the constraint geometry and pads.

protected void AdjustForGravity(GridBagConstraints constraints, Rectangle r)

This method is obsolete and supplied for backwards compatability only; new code should call adjustForGravity instead.

protected void arrangeGrid(Container parent)

Lays out the grid.

protected void ArrangeGrid(Container parent)

This method is obsolete and supplied for backwards compatability only; new code should call arrangeGrid instead.

GridBagConstraints getConstraints(Component comp)

Gets the constraints for the specified component.

float getLayoutAlignmentX(Container parent)

Returns the alignment along the x axis.

float getLayoutAlignmentY(Container parent)

Returns the alignment along the y axis.

int[][] getLayoutDimensions()

Determines column widths and row heights for the layout grid.

protected java.awt.GridBagLayoutInfo getLayoutInfo(Container parent, int sizeflag)

Fills in an instance of GridBagLayoutInfo for the current set of managed children.

protected java.awt.GridBagLayoutInfo GetLayoutInfo(Container parent, int sizeflag)

This method is obsolete and supplied for backwards compatability only; new code should call getLayoutInfo instead.

Point getLayoutOrigin()

Determines the origin of the layout area, in the graphics coordinate space of the target container.

double[][] getLayoutWeights()

Determines the weights of the layout grid’s columns and rows.

protected Dimension getMinSize(Container parent, java.awt.GridBagLayoutInfo info)

Figures out the minimum size of the master based on the information from getLayoutInfo().

protected Dimension GetMinSize(Container parent, java.awt.GridBagLayoutInfo info)

This method is obsolete and supplied for backwards compatability only; new code should call getMinSize instead.

void invalidateLayout(Container target)

Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.

void layoutContainer(Container parent)

Lays out the specified container using this grid bag layout.

Point location(int x, int y)

Determines which cell in the layout grid contains the point specified by (x, y).

protected GridBagConstraints lookupConstraints(Component comp)

Retrieves the constraints for the specified component.

Dimension maximumLayoutSize(Container target)

Returns the maximum dimensions for this layout given the components in the specified target container.

Dimension minimumLayoutSize(Container parent)

Determines the minimum size of the parent container using this grid bag layout.

Dimension preferredLayoutSize(Container parent)

Determines the preferred size of the parent container using this grid bag layout.

void removeLayoutComponent(Component comp)

Removes the specified component from this layout.

void setConstraints(Component comp, GridBagConstraints constraints)

Sets the constraints for the specified component in this layout.

Строка toString ()

Returns a string representation of this grid bag layout’s values.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.lang.Object

java.lang.Object

GridBagLayout Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtLayoutDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtLayoutDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;
   private Label msglabel;

   public AwtLayoutDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtLayoutDemo  awtLayoutDemo = new AwtLayoutDemo();  
      awtLayoutDemo.showGridBagLayoutDemo();       
   }
      
   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      msglabel = new Label();
      msglabel.setAlignment(Label.CENTER);
      msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showGridBagLayoutDemo(){
      headerLabel.setText("Layout in action: GridBagLayout");      

      Panel panel = new Panel();
      panel.setBackground(Color.darkGray);
      panel.setSize(300,300);
      GridBagLayout layout = new GridBagLayout();

      panel.setLayout(layout);        
      GridBagConstraints gbc = new GridBagConstraints();

      gbc.fill = GridBagConstraints.HORIZONTAL;
      gbc.gridx = 0;
      gbc.gridy = 0;
      panel.add(new Button("Button 1"),gbc);

      gbc.gridx = 1;
      gbc.gridy = 0;
      panel.add(new Button("Button 2"),gbc); 

      gbc.fill = GridBagConstraints.HORIZONTAL;
      gbc.ipady = 20;   
      gbc.gridx = 0;
      gbc.gridy = 1;
      panel.add(new Button("Button 3"),gbc); 

      gbc.gridx = 1;
      gbc.gridy = 1;       
      panel.add(new Button("Button 4"),gbc);  

      gbc.gridx = 0;
      gbc.gridy = 2;      
      gbc.fill = GridBagConstraints.HORIZONTAL;
      gbc.gridwidth = 2;
      panel.add(new Button("Button 5"),gbc);  

      controlPanel.add(panel);

      mainFrame.setVisible(true);  
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtlayoutDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtlayoutDemo

Проверьте следующий вывод

AWT GridBagLayout

AWT Контейнеры

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

  • Подклассы Контейнера называются Контейнером. Например, Панель, Рамка и Окно.

  • Контейнер может добавить только Компонент к себе.

  • Макет по умолчанию присутствует в каждом контейнере, который можно переопределить с помощью метода setLayout.

Подклассы Контейнера называются Контейнером. Например, Панель, Рамка и Окно.

Контейнер может добавить только Компонент к себе.

Макет по умолчанию присутствует в каждом контейнере, который можно переопределить с помощью метода setLayout.

AWT Container Class

Вступление

The class Container is the super class for the containers of AWT. Container object can contain other AWT components.

Объявление класса

Following is the declaration for java.awt.Container class:

public class Container
   extends Component

Конструкторы классов

SN Конструктор и описание
1

Container()

This creates a new Container.

Container()

This creates a new Container.

Методы класса

SN Метод и описание
1

Component add(Component comp)

Appends the specified component to the end of this container.

2

Component add(Component comp, int index)

Adds the specified component to this container at the given position.

3

void add(Component comp, Object constraints)

Adds the specified component to the end of this container.

4

void add(Component comp, Object constraints, int index)

Adds the specified component to this container with the specified constraints at the specified index.

5

Component add(String name, Component comp)

Adds the specified component to this container.

6

void addContainerListener(ContainerListener l)

Adds the specified container listener to receive container events from this container.

7

protected void addImpl(Component comp, Object constraints, int index)

Adds the specified component to this container at the specified index.

8

void addNotify()

Makes this Container displayable by connecting it to a native screen resource.

9

void addPropertyChangeListener(PropertyChangeListener listener)

Adds a PropertyChangeListener to the listener list.

10

void addPropertyChangeListener(String propertyName, PropertyChangeListener listener)

Adds a PropertyChangeListener to the listener list for a specific property.

11

void applyComponentOrientation(ComponentOrientation o)

Sets the ComponentOrientation property of this container and all components contained within it.

12

boolean areFocusTraversalKeysSet(int id)

Returns whether the Set of focus traversal keys for the given focus traversal operation has been explicitly defined for this Container.

13

int countComponents()

Устаревшее. As of JDK version 1.1, replaced by getComponentCount().

14

void deliverEvent(Event e)

Устаревшее. As of JDK version 1.1, replaced by dispatchEvent(AWTEvent e)

15

void doLayout()

Causes this container to lay out its components.

16

Component findComponentAt(int x, int y)

Locates the visible child component that contains the specified position.

17

Component findComponentAt(Point p)

Locates the visible child component that contains the specified point.

18

float getAlignmentX()

Returns the alignment along the x axis.

19

float getAlignmentY()

Returns the alignment along the y axis.

20

Component getComponent(int n)

Gets the nth component in this container.

21

Component getComponentAt(int x, int y)

Locates the component that contains the x,y position.

22

Component getComponentAt(Point p)

Gets the component that contains the specified point.

23

int getComponentCount()

Gets the number of components in this panel.

24

Component[] getComponents()

Gets all the components in this container.

25

int getComponentZOrder(Component comp)

Returns the z-order index of the component inside the container.

26

ContainerListener[] getContainerListeners()

Returns an array of all the container listeners registered on this container.

27

Set<AWTKeyStroke> getFocusTraversalKeys(int id)

Returns the Set of focus traversal keys for a given traversal operation for this Container.

28

FocusTraversalPolicy getFocusTraversalPolicy()

Returns the focus traversal policy that will manage keyboard traversal of this Container’s children, or null if this Container is not a focus cycle root.

29

Insets getInsets()

Determines the insets of this container, which indicate the size of the container’s border.

30

LayoutManager getLayout()

Gets the layout manager for this container.

31

<T extends EventListener> T[] getListeners(Class<T> listenerType)

Returns an array of all the objects currently registered as FooListeners upon this Container.

32

Dimension getMaximumSize()

Returns the maximum size of this container.

33

Dimension getMinimumSize()

Returns the minimum size of this container.

34

Point getMousePosition(boolean allowChildren)

Returns the position of the mouse pointer in this Container’s coordinate space if the Container is under the mouse pointer, otherwise returns null.

35

Dimension getPreferredSize()

Returns the preferred size of this container.

36

Insets insets()

Устаревшее. As of JDK version 1.1, replaced by getInsets().

37

void invalidate()

Invalidates the container.

38

boolean isAncestorOf(Component c)

Checks if the component is contained in the component hierarchy of this container.

39

boolean isFocusCycleRoot()

Returns whether this Container is the root of a focus traversal cycle.

40

boolean isFocusCycleRoot(Container container)

Returns whether the specified Container is the focus cycle root of this Container’s focus traversal cycle.

41

boolean isFocusTraversalPolicyProvider()

Returns whether this container provides focus traversal policy.

42

boolean isFocusTraversalPolicySet()

Returns whether the focus traversal policy has been explicitly set for this Container.

43

void layout()

Устаревшее. As of JDK version 1.1, replaced by doLayout().

44

void list(PrintStream out, int indent)

Prints a listing of this container to the specified output stream.

45

void list(PrintWriter out, int indent)

Prints out a list, starting at the specified indentation, to the specified print writer.

46

Component locate(int x, int y)

Устаревшее. As of JDK version 1.1, replaced by getComponentAt(int, int).

47

Dimension minimumSize()

Устаревшее. As of JDK version 1.1, replaced by getMinimumSize().

48

void paint(Graphics g)

Paints the container.

49

void paintComponents(Graphics g)

Paints each of the components in this container.

50

protected String paramString()

Returns a string representing the state of this Container.

51

Dimension preferredSize()

Устаревшее. As of JDK version 1.1, replaced by getPreferredSize().

52

void print(Graphics g)

Prints the container.

53

void printComponents(Graphics g)

Prints each of the components in this container.

54

protected void processContainerEvent(ContainerEvent e)

Processes container events occurring on this container by dispatching them to any registered ContainerListener objects.

55

protected void processEvent(AWTEvent e)

Processes events on this container.

56

void remove(Component comp)

Removes the specified component from this container.

57

void remove(int index)

Removes the component, specified by index, from this container.

58

void removeAll()

Removes all the components from this container.

59

void removeContainerListener(ContainerListener l)

Removes the specified container listener so it no longer receives container events from this container.

60

void removeNotify()

Makes this Container undisplayable by removing its connection to its native screen resource.

61

void setComponentZOrder(Component comp, int index)

Moves the specified component to the specified z-order index in the container.

62

void setFocusCycleRoot(boolean focusCycleRoot)

Sets whether this Container is the root of a focus traversal cycle.

63

void setFocusTraversalKeys(int id, Set<? extends AWTKeyStroke> keystrokes)

Sets the focus traversal keys for a given traversal operation for this Container.

64

void setFocusTraversalPolicy(FocusTraversalPolicy policy)

Sets the focus traversal policy that will manage keyboard traversal of this Container’s children, if this Container is a focus cycle root.

65

void setFocusTraversalPolicyProvider(boolean provider)

Sets whether this container will be used to provide focus traversal policy.

66

void setFont(Font f)

Sets the font of this container.

67

void setLayout(LayoutManager mgr)

Sets the layout manager for this container.

68

void transferFocusBackward()

Transfers the focus to the previous component, as though this Component were the focus owner.

69

void transferFocusDownCycle()

Transfers the focus down one focus traversal cycle.

70

void update(Graphics g)

Updates the container.

71

void validate()

Validates this container and all of its subcomponents.

72

protected void validateTree()

Recursively descends the container tree and recomputes the layout for any subtrees marked as needing it (those marked as invalid).

Component add(Component comp)

Appends the specified component to the end of this container.

Component add(Component comp, int index)

Adds the specified component to this container at the given position.

void add(Component comp, Object constraints)

Adds the specified component to the end of this container.

void add(Component comp, Object constraints, int index)

Adds the specified component to this container with the specified constraints at the specified index.

Component add(String name, Component comp)

Adds the specified component to this container.

void addContainerListener(ContainerListener l)

Adds the specified container listener to receive container events from this container.

protected void addImpl(Component comp, Object constraints, int index)

Adds the specified component to this container at the specified index.

void addNotify()

Makes this Container displayable by connecting it to a native screen resource.

void addPropertyChangeListener(PropertyChangeListener listener)

Adds a PropertyChangeListener to the listener list.

void addPropertyChangeListener(String propertyName, PropertyChangeListener listener)

Adds a PropertyChangeListener to the listener list for a specific property.

void applyComponentOrientation(ComponentOrientation o)

Sets the ComponentOrientation property of this container and all components contained within it.

boolean areFocusTraversalKeysSet(int id)

Returns whether the Set of focus traversal keys for the given focus traversal operation has been explicitly defined for this Container.

int countComponents()

Устаревшее. As of JDK version 1.1, replaced by getComponentCount().

void deliverEvent(Event e)

Устаревшее. As of JDK version 1.1, replaced by dispatchEvent(AWTEvent e)

void doLayout()

Causes this container to lay out its components.

Component findComponentAt(int x, int y)

Locates the visible child component that contains the specified position.

Component findComponentAt(Point p)

Locates the visible child component that contains the specified point.

float getAlignmentX()

Returns the alignment along the x axis.

float getAlignmentY()

Returns the alignment along the y axis.

Component getComponent(int n)

Gets the nth component in this container.

Component getComponentAt(int x, int y)

Locates the component that contains the x,y position.

Component getComponentAt(Point p)

Gets the component that contains the specified point.

int getComponentCount()

Gets the number of components in this panel.

Component[] getComponents()

Gets all the components in this container.

int getComponentZOrder(Component comp)

Returns the z-order index of the component inside the container.

ContainerListener[] getContainerListeners()

Returns an array of all the container listeners registered on this container.

Set<AWTKeyStroke> getFocusTraversalKeys(int id)

Returns the Set of focus traversal keys for a given traversal operation for this Container.

FocusTraversalPolicy getFocusTraversalPolicy()

Returns the focus traversal policy that will manage keyboard traversal of this Container’s children, or null if this Container is not a focus cycle root.

Insets getInsets()

Determines the insets of this container, which indicate the size of the container’s border.

LayoutManager getLayout()

Gets the layout manager for this container.

<T extends EventListener> T[] getListeners(Class<T> listenerType)

Returns an array of all the objects currently registered as FooListeners upon this Container.

Dimension getMaximumSize()

Returns the maximum size of this container.

Dimension getMinimumSize()

Returns the minimum size of this container.

Point getMousePosition(boolean allowChildren)

Returns the position of the mouse pointer in this Container’s coordinate space if the Container is under the mouse pointer, otherwise returns null.

Dimension getPreferredSize()

Returns the preferred size of this container.

Insets insets()

Устаревшее. As of JDK version 1.1, replaced by getInsets().

void invalidate()

Invalidates the container.

boolean isAncestorOf(Component c)

Checks if the component is contained in the component hierarchy of this container.

boolean isFocusCycleRoot()

Returns whether this Container is the root of a focus traversal cycle.

boolean isFocusCycleRoot(Container container)

Returns whether the specified Container is the focus cycle root of this Container’s focus traversal cycle.

boolean isFocusTraversalPolicyProvider()

Returns whether this container provides focus traversal policy.

boolean isFocusTraversalPolicySet()

Returns whether the focus traversal policy has been explicitly set for this Container.

void layout()

Устаревшее. As of JDK version 1.1, replaced by doLayout().

void list(PrintStream out, int indent)

Prints a listing of this container to the specified output stream.

void list(PrintWriter out, int indent)

Prints out a list, starting at the specified indentation, to the specified print writer.

Component locate(int x, int y)

Устаревшее. As of JDK version 1.1, replaced by getComponentAt(int, int).

Dimension minimumSize()

Устаревшее. As of JDK version 1.1, replaced by getMinimumSize().

void paint(Graphics g)

Paints the container.

void paintComponents(Graphics g)

Paints each of the components in this container.

protected String paramString()

Returns a string representing the state of this Container.

Dimension preferredSize()

Устаревшее. As of JDK version 1.1, replaced by getPreferredSize().

void print(Graphics g)

Prints the container.

void printComponents(Graphics g)

Prints each of the components in this container.

protected void processContainerEvent(ContainerEvent e)

Processes container events occurring on this container by dispatching them to any registered ContainerListener objects.

protected void processEvent(AWTEvent e)

Processes events on this container.

void remove(Component comp)

Removes the specified component from this container.

void remove(int index)

Removes the component, specified by index, from this container.

void removeAll()

Removes all the components from this container.

void removeContainerListener(ContainerListener l)

Removes the specified container listener so it no longer receives container events from this container.

void removeNotify()

Makes this Container undisplayable by removing its connection to its native screen resource.

void setComponentZOrder(Component comp, int index)

Moves the specified component to the specified z-order index in the container.

void setFocusCycleRoot(boolean focusCycleRoot)

Sets whether this Container is the root of a focus traversal cycle.

void setFocusTraversalKeys(int id, Set<? extends AWTKeyStroke> keystrokes)

Sets the focus traversal keys for a given traversal operation for this Container.

void setFocusTraversalPolicy(FocusTraversalPolicy policy)

Sets the focus traversal policy that will manage keyboard traversal of this Container’s children, if this Container is a focus cycle root.

void setFocusTraversalPolicyProvider(boolean provider)

Sets whether this container will be used to provide focus traversal policy.

void setFont(Font f)

Sets the font of this container.

void setLayout(LayoutManager mgr)

Sets the layout manager for this container.

void transferFocusBackward()

Transfers the focus to the previous component, as though this Component were the focus owner.

void transferFocusDownCycle()

Transfers the focus down one focus traversal cycle.

void update(Graphics g)

Updates the container.

void validate()

Validates this container and all of its subcomponents.

protected void validateTree()

Recursively descends the container tree and recomputes the layout for any subtrees marked as needing it (those marked as invalid).

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.awt.Component

  • java.lang.Object

java.awt.Component

java.lang.Object

AWT Panel Class

Вступление

The class Panel is the simplest container class. It provides space in which an application can attach any other component, including other panels. It uses FlowLayout as default layout manager.

Объявление класса

Following is the declaration for java.awt.Panel class:

public class Panel
   extends Container
      implements Accessible

Конструкторы классов

SN Конструктор и описание
1

Panel()

Creates a new panel using the default layout manager.

2

Panel(LayoutManager layout)

Creates a new panel with the specified layout manager.

Panel()

Creates a new panel using the default layout manager.

Panel(LayoutManager layout)

Creates a new panel with the specified layout manager.

Методы класса

SN Метод и описание
1

void addNotify()

Creates the Panel’s peer.

2

AccessibleContext getAccessibleContext()

Gets the AccessibleContext associated with this Panel.

void addNotify()

Creates the Panel’s peer.

AccessibleContext getAccessibleContext()

Gets the AccessibleContext associated with this Panel.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

java.awt.Container

java.awt.Component

java.lang.Object

Panel Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtContainerDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtContainerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;
   private Label msglabel;

   public AwtContainerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtContainerDemo  awtContainerDemo = new AwtContainerDemo();          
      awtContainerDemo.showPanelDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);
   
      msglabel = new Label();
      msglabel.setAlignment(Label.CENTER);
      msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showPanelDemo(){
      headerLabel.setText("Container in action: Panel");      

      Panel panel = new Panel();
      panel.setBackground(Color.magenta);
      panel.setLayout(new FlowLayout());        
      panel.add(msglabel);

      controlPanel.add(panel);

      mainFrame.setVisible(true);  
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtContainerDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtContainerDemo

Проверьте следующий вывод

AWT Panel

AWT Frame Class

Вступление

The class Frame is a top level window with border and title. It uses BorderLayout as default layout manager.

Объявление класса

Following is the declaration for java.awt.Frame class:

public class Frame
   extends Window
      implements MenuContainer

поле

Following are the fields for java.awt.Frame class:

  • static float BOTTOM_ALIGNMENT — Ease-of-use constant for getAlignmentY.

  • static int CROSSHAIR_CURSOR — Deprecated. replaced by Cursor.CROSSHAIR_CURSOR.

  • static int DEFAULT_CURSOR — Deprecated. replaced by Cursor.DEFAULT_CURSOR.

  • static int E_RESIZE_CURSOR — Deprecated. replaced by Cursor.E_RESIZE_CURSOR.

  • static int HAND_CURSOR — Deprecated. replaced by Cursor.HAND_CURSOR.

  • static int ICONIFIED — This state bit indicates that frame is iconified.

  • static int MAXIMIZED_BOTH — This state bit mask indicates that frame is fully maximized (that is both horizontally and vertically).

  • static int MAXIMIZED_HORIZ — This state bit indicates that frame is maximized in the horizontal direction.

  • static int MAXIMIZED_VERT — This state bit indicates that frame is maximized in the vertical direction.

  • static int MOVE_CURSOR — Deprecated. replaced by Cursor.MOVE_CURSOR.

  • static int N_RESIZE_CURSOR — Deprecated. replaced by Cursor.N_RESIZE_CURSOR.

  • static int NE_RESIZE_CURSOR — Deprecated. replaced by Cursor.NE_RESIZE_CURSOR.

  • static int NORMAL — Frame is in the “normal” state.

  • static int NW_RESIZE_CURSOR — Deprecated. replaced by Cursor.NW_RESIZE_CURSOR.

  • static int S_RESIZE_CURSOR — Deprecated. replaced by Cursor.S_RESIZE_CURSOR.

  • static int SE_RESIZE_CURSOR — Deprecated. replaced by Cursor.SE_RESIZE_CURSOR.

  • static int SW_RESIZE_CURSOR — Deprecated. replaced by Cursor.SW_RESIZE_CURSOR.

  • static int TEXT_CURSOR — Deprecated. replaced by Cursor.TEXT_CURSOR.

  • static int W_RESIZE_CURSOR — Deprecated. replaced by Cursor.W_RESIZE_CURSOR.

  • static int WAIT_CURSOR — Deprecated. replaced by Cursor.WAIT_CURSOR.

static float BOTTOM_ALIGNMENT — Ease-of-use constant for getAlignmentY.

static int CROSSHAIR_CURSOR — Deprecated. replaced by Cursor.CROSSHAIR_CURSOR.

static int DEFAULT_CURSOR — Deprecated. replaced by Cursor.DEFAULT_CURSOR.

static int E_RESIZE_CURSOR — Deprecated. replaced by Cursor.E_RESIZE_CURSOR.

static int HAND_CURSOR — Deprecated. replaced by Cursor.HAND_CURSOR.

static int ICONIFIED — This state bit indicates that frame is iconified.

static int MAXIMIZED_BOTH — This state bit mask indicates that frame is fully maximized (that is both horizontally and vertically).

static int MAXIMIZED_HORIZ — This state bit indicates that frame is maximized in the horizontal direction.

static int MAXIMIZED_VERT — This state bit indicates that frame is maximized in the vertical direction.

static int MOVE_CURSOR — Deprecated. replaced by Cursor.MOVE_CURSOR.

static int N_RESIZE_CURSOR — Deprecated. replaced by Cursor.N_RESIZE_CURSOR.

static int NE_RESIZE_CURSOR — Deprecated. replaced by Cursor.NE_RESIZE_CURSOR.

static int NORMAL — Frame is in the “normal” state.

static int NW_RESIZE_CURSOR — Deprecated. replaced by Cursor.NW_RESIZE_CURSOR.

static int S_RESIZE_CURSOR — Deprecated. replaced by Cursor.S_RESIZE_CURSOR.

static int SE_RESIZE_CURSOR — Deprecated. replaced by Cursor.SE_RESIZE_CURSOR.

static int SW_RESIZE_CURSOR — Deprecated. replaced by Cursor.SW_RESIZE_CURSOR.

static int TEXT_CURSOR — Deprecated. replaced by Cursor.TEXT_CURSOR.

static int W_RESIZE_CURSOR — Deprecated. replaced by Cursor.W_RESIZE_CURSOR.

static int WAIT_CURSOR — Deprecated. replaced by Cursor.WAIT_CURSOR.

Конструкторы классов

SN Конструктор и описание
1

Frame()

Constructs a new instance of Frame that is initially invisible.

2

Frame(GraphicsConfiguration gc)

Constructs a new, initially invisible Frame with the specified GraphicsConfiguration.

3

Frame(String title)

Constructs a new, initially invisible Frame object with the specified title.

4

Frame(String title, GraphicsConfiguration gc)

Constructs a new, initially invisible Frame object with the specified title and a GraphicsConfiguration.

Frame()

Constructs a new instance of Frame that is initially invisible.

Frame(GraphicsConfiguration gc)

Constructs a new, initially invisible Frame with the specified GraphicsConfiguration.

Frame(String title)

Constructs a new, initially invisible Frame object with the specified title.

Frame(String title, GraphicsConfiguration gc)

Constructs a new, initially invisible Frame object with the specified title and a GraphicsConfiguration.

Методы класса

SN Метод и описание
1

void addNotify()

Makes this Frame displayable by connecting it to a native screen resource.

2

AccessibleContext getAccessibleContext()

Gets the AccessibleContext associated with this Frame.

3

int getCursorType()

Устаревшее. As of JDK version 1.1, replaced by Component.getCursor().

4

int getExtendedState()

Gets the state of this frame.

5

static Frame[] getFrames()

Returns an array of all Frames created by this application.

6

Image getIconImage()

Returns the image to be displayed as the icon for this frame.

7

Rectangle getMaximizedBounds()

Gets maximized bounds for this frame.

8

MenuBar getMenuBar()

Gets the menu bar for this frame.

9

int getState()

Gets the state of this frame (obsolete).

10

String getTitle()

Gets the title of the frame.

11

boolean isResizable()

Indicates whether this frame is resizable by the user.

12

boolean isUndecorated()

Indicates whether this frame is undecorated.

13

protected String paramString()

Returns a string representing the state of this Frame.

14

void remove(MenuComponent m)

Removes the specified menu bar from this frame.

15

void removeNotify()

Makes this Frame undisplayable by removing its connection to its native screen resource.

16

void setCursor(int cursorType)

Устаревшее. As of JDK version 1.1, replaced by Component.setCursor(Cursor).

17

void setExtendedState(int state)

Sets the state of this frame.

18

void setIconImage(Image image)

Sets the image to be displayed as the icon for this window.

19

void setMaximizedBounds(Rectangle bounds)

Sets the maximized bounds for this frame.

20

void setMenuBar(MenuBar mb)

Sets the menu bar for this frame to the specified menu bar.

21

void setResizable(boolean resizable)

Sets whether this frame is resizable by the user.

22

void setState(int state)

Sets the state of this frame (obsolete).

23

void setTitle(String title)

Sets the title for this frame to the specified string.

24

void setUndecorated(boolean undecorated)

Disables or enables decorations for this frame.

void addNotify()

Makes this Frame displayable by connecting it to a native screen resource.

AccessibleContext getAccessibleContext()

Gets the AccessibleContext associated with this Frame.

int getCursorType()

Устаревшее. As of JDK version 1.1, replaced by Component.getCursor().

int getExtendedState()

Gets the state of this frame.

static Frame[] getFrames()

Returns an array of all Frames created by this application.

Image getIconImage()

Returns the image to be displayed as the icon for this frame.

Rectangle getMaximizedBounds()

Gets maximized bounds for this frame.

MenuBar getMenuBar()

Gets the menu bar for this frame.

int getState()

Gets the state of this frame (obsolete).

String getTitle()

Gets the title of the frame.

boolean isResizable()

Indicates whether this frame is resizable by the user.

boolean isUndecorated()

Indicates whether this frame is undecorated.

protected String paramString()

Returns a string representing the state of this Frame.

void remove(MenuComponent m)

Removes the specified menu bar from this frame.

void removeNotify()

Makes this Frame undisplayable by removing its connection to its native screen resource.

void setCursor(int cursorType)

Устаревшее. As of JDK version 1.1, replaced by Component.setCursor(Cursor).

void setExtendedState(int state)

Sets the state of this frame.

void setIconImage(Image image)

Sets the image to be displayed as the icon for this window.

void setMaximizedBounds(Rectangle bounds)

Sets the maximized bounds for this frame.

void setMenuBar(MenuBar mb)

Sets the menu bar for this frame to the specified menu bar.

void setResizable(boolean resizable)

Sets whether this frame is resizable by the user.

void setState(int state)

Sets the state of this frame (obsolete).

void setTitle(String title)

Sets the title for this frame to the specified string.

void setUndecorated(boolean undecorated)

Disables or enables decorations for this frame.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.awt.Window

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

java.awt.Window

java.awt.Container

java.awt.Component

java.lang.Object

Frame Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtContainerDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtContainerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;
   private Label msglabel;

   public AwtContainerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtContainerDemo  awtContainerDemo = new AwtContainerDemo();          
      awtContainerDemo.showFrameDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);
   
      msglabel = new Label();
      msglabel.setAlignment(Label.CENTER);
      msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   
   private void showFrameDemo(){
      headerLabel.setText("Container in action: Frame");   

      final Frame frame = new Frame();
      frame.setSize(300, 300);
      frame.setLayout(new FlowLayout());       
      frame.add(msglabel);
      frame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            frame.dispose();
         }        
      });    
      Button okButton = new Button("Open a Frame");

      okButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            statusLabel.setText("A Frame shown to the user.");
            frame.setVisible(true);
         }
      });
      controlPanel.add(okButton);

      mainFrame.setVisible(true);  
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtContainerDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtContainerDemo

Проверьте следующий вывод

AWT Frame

AWT Window Class

Вступление

The class Window is a top level window with no border and no menubar. It uses BorderLayout as default layout manager.

Объявление класса

Following is the declaration for java.awt.Window class:

public class Window
   extends Container
      implements Accessible

Конструкторы классов

SN Конструктор и описание
1

Window(Frame owner)

Constructs a new, initially invisible window with the specified Frame as its owner.

2

Window(Window owner)

Constructs a new, initially invisible window with the specified Window as its owner.

3

Window(Window owner, GraphicsConfiguration gc)

Constructs a new, initially invisible window with the specified owner Window and a GraphicsConfiguration of a screen device.

Window(Frame owner)

Constructs a new, initially invisible window with the specified Frame as its owner.

Window(Window owner)

Constructs a new, initially invisible window with the specified Window as its owner.

Window(Window owner, GraphicsConfiguration gc)

Constructs a new, initially invisible window with the specified owner Window and a GraphicsConfiguration of a screen device.

Методы класса

SN Метод и описание
1

void addNotify()

Makes this Window displayable by creating the connection to its native screen resource.

2

void addPropertyChangeListener(PropertyChangeListener listener)

Adds a PropertyChangeListener to the listener list.

3

void addPropertyChangeListener(String propertyName, PropertyChangeListener listener)

Adds a PropertyChangeListener to the listener list for a specific property.

4

void addWindowFocusListener(WindowFocusListener l)

Adds the specified window focus listener to receive window events from this window.

5

void addWindowListener(WindowListener l)

Adds the specified window listener to receive window events from this window.

6

void addWindowStateListener(WindowStateListener l)

Adds the specified window state listener to receive window events from this window.

7

void applyResourceBundle(ResourceBundle rb)

Устаревшее. As of J2SE 1.4, replaced by Component.applyComponentOrientation.

8

void applyResourceBundle(String rbName)

Устаревшее. As of J2SE 1.4, replaced by Component.applyComponentOrientation.

9

void createBufferStrategy(int numBuffers)

Creates a new strategy for multi-buffering on this component.

10

void createBufferStrategy(int numBuffers, BufferCapabilities caps)

Creates a new strategy for multi-buffering on this component with the required buffer capabilities.

11

void dispose()

Releases all of the native screen resources used by this Window, its subcomponents, and all of its owned children.

12

AccessibleContext getAccessibleContext()

Gets the AccessibleContext associated with this Window.

13

BufferStrategy getBufferStrategy()

Returns the BufferStrategy used by this component.

14

boolean getFocusableWindowState()

Returns whether this Window can become the focused Window if it meets the other requirements outlined in isFocusableWindow.

15

Container getFocusCycleRootAncestor()

Always returns null because Windows have no ancestors; they represent the top of the Component hierarchy.

16

Component getFocusOwner()

Returns the child Component of this Window that has focus if this Window is focused; returns null otherwise.

17

Set<AWTKeyStroke> getFocusTraversalKeys(int id)

Gets a focus traversal key for this Window.

18

GraphicsConfiguration getGraphicsConfiguration()

This method returns the GraphicsConfiguration used by this Window.

19

List<Image> getIconImages()

Returns the sequence of images to be displayed as the icon for this window.

20

InputContext getInputContext()

Gets the input context for this window.

21

<T extends EventListener> T[] getListeners(Class<T> listenerType)

Returns an array of all the objects currently registered as FooListeners upon this Window.

22

Locale getLocale ()

Gets the Locale object that is associated with this window, if the locale has been set.

23

Dialog.ModalExclusionType getModalExclusionType()

Returns the modal exclusion type of this window.

24

Component getMostRecentFocusOwner()

Returns the child Component of this Window that will receive the focus when this Window is focused.

25

Window[] getOwnedWindows()

Return an array containing all the windows this window currently owns.

26

Window getOwner()

Returns the owner of this window.

27

static Window[] getOwnerlessWindows()

Returns an array of all Windows created by this application that have no owner.

28

Toolkit getToolkit()

Returns the toolkit of this frame.

29

String getWarningString()

Gets the warning string that is displayed with this window.

30

WindowFocusListener[] getWindowFocusListeners()

Returns an array of all the window focus listeners registered on this window.

31

WindowListener[] getWindowListeners()

Returns an array of all the window listeners registered on this window.

32

static Window[] getWindows()

Returns an array of all Windows, both owned and ownerless, created by this application.

33

WindowStateListener[] getWindowStateListeners()

Returns an array of all the window state listeners registered on this window.

34

void hide()

Устаревшее. As of JDK version 1.5, replaced by setVisible(boolean).

35

boolean isActive()

Returns whether this Window is active.

36

boolean isAlwaysOnTop()

Returns whether this window is an always-on-top window.

37

boolean isAlwaysOnTopSupported()

Returns whether the always-on-top mode is supported for this window.

38

boolean isFocusableWindow()

Returns whether this Window can become the focused Window, that is, whether this Window or any of its subcomponents can become the focus owner.

39

boolean isFocusCycleRoot()

Always returns true because all Windows must be roots of a focus traversal cycle.

40

boolean isFocused()

Returns whether this Window is focused.

41

boolean isLocationByPlatform()

Returns true if this Window will appear at the default location for the native windowing system the next time this Window is made visible.

42

boolean isShowing()

Checks if this Window is showing on screen.

43

void pack()

Causes this Window to be sized to fit the preferred size and layouts of its subcomponents.

44

void paint(Graphics g)

Paints the container.

45

boolean postEvent(Event e)

Устаревшее. As of JDK version 1.1 replaced by dispatchEvent(AWTEvent).

46

protected void processEvent(AWTEvent e)

Processes events on this window.

47

protected void processWindowEvent(WindowEvent e)

Processes window events occurring on this window by dispatching them to any registered WindowListener objects.

48

protected void processWindowFocusEvent(WindowEvent e)

Processes window focus event occuring on this window by dispatching them to any registered WindowFocusListener objects.

49

protected void processWindowStateEvent(WindowEvent e)

Processes window state event occuring on this window by dispatching them to any registered WindowStateListener objects.

50

void removeNotify()

Makes this Container undisplayable by removing its connection to its native screen resource.

51

void removeWindowFocusListener(WindowFocusListener l)

Removes the specified window focus listener so that it no longer receives window events from this window.

52

void removeWindowListener(WindowListener l)

Removes the specified window listener so that it no longer receives window events from this window.

53

void removeWindowStateListener(WindowStateListener l)

Removes the specified window state listener so that it no longer receives window events from this window.

54

void reshape(int x, int y, int width, int height)

Устаревшее. As of JDK version 1.1, replaced by setBounds(int, int, int, int).

55

void setAlwaysOnTop(boolean alwaysOnTop)

Sets whether this window should always be above other windows.

56

void setBounds(int x, int y, int width, int height)

Moves and resizes this component.

57

void setBounds(Rectangle r)

Moves and resizes this component to conform to the new bounding rectangle r.

58

void setCursor(Cursor cursor)

Set the cursor image to a specified cursor.

59

void setFocusableWindowState(boolean focusableWindowState)

Sets whether this Window can become the focused Window if it meets the other requirements outlined in isFocusableWindow.

60

void setFocusCycleRoot(boolean focusCycleRoot)

Does nothing because Windows must always be roots of a focus traversal cycle.

61

void setIconImage(Image image)

Sets the image to be displayed as the icon for this window.

62

void setIconImages(List<? extends Image> icons)

Sets the sequence of images to be displayed as the icon for this window.

63

void setLocationByPlatform(boolean locationByPlatform)

Sets whether this Window should appear at the default location for the native windowing system or at the current location (returned by getLocation) the next time the Window is made visible.

64

void setLocationRelativeTo(Component c)

Sets the location of the window relative to the specified component.

65

void setMinimumSize(Dimension minimumSize)

Sets the minimum size of this window to a constant value.

66

void setModalExclusionType(Dialog.ModalExclusionType exclusionType)

Specifies the modal exclusion type for this window.

67

void setSize(Dimension d)

Resizes this component so that it has width d.width and height d.height.

68

void setSize(int width, int height)

Resizes this component so that it has width width and height height.

69

void setVisible(boolean b)

Shows or hides this Window depending on the value of parameter b.

70

void show()

Устаревшее. As of JDK version 1.5, replaced by setVisible(boolean).

71

void toBack()

If this Window is visible, sends this Window to the back and may cause it to lose focus or activation if it is the focused or active Window.

72

void toFront()

If this Window is visible, brings this Window to the front and may make it the focused Window.

void addNotify()

Makes this Window displayable by creating the connection to its native screen resource.

void addPropertyChangeListener(PropertyChangeListener listener)

Adds a PropertyChangeListener to the listener list.

void addPropertyChangeListener(String propertyName, PropertyChangeListener listener)

Adds a PropertyChangeListener to the listener list for a specific property.

void addWindowFocusListener(WindowFocusListener l)

Adds the specified window focus listener to receive window events from this window.

void addWindowListener(WindowListener l)

Adds the specified window listener to receive window events from this window.

void addWindowStateListener(WindowStateListener l)

Adds the specified window state listener to receive window events from this window.

void applyResourceBundle(ResourceBundle rb)

Устаревшее. As of J2SE 1.4, replaced by Component.applyComponentOrientation.

void applyResourceBundle(String rbName)

Устаревшее. As of J2SE 1.4, replaced by Component.applyComponentOrientation.

void createBufferStrategy(int numBuffers)

Creates a new strategy for multi-buffering on this component.

void createBufferStrategy(int numBuffers, BufferCapabilities caps)

Creates a new strategy for multi-buffering on this component with the required buffer capabilities.

void dispose()

Releases all of the native screen resources used by this Window, its subcomponents, and all of its owned children.

AccessibleContext getAccessibleContext()

Gets the AccessibleContext associated with this Window.

BufferStrategy getBufferStrategy()

Returns the BufferStrategy used by this component.

boolean getFocusableWindowState()

Returns whether this Window can become the focused Window if it meets the other requirements outlined in isFocusableWindow.

Container getFocusCycleRootAncestor()

Always returns null because Windows have no ancestors; they represent the top of the Component hierarchy.

Component getFocusOwner()

Returns the child Component of this Window that has focus if this Window is focused; returns null otherwise.

Set<AWTKeyStroke> getFocusTraversalKeys(int id)

Gets a focus traversal key for this Window.

GraphicsConfiguration getGraphicsConfiguration()

This method returns the GraphicsConfiguration used by this Window.

List<Image> getIconImages()

Returns the sequence of images to be displayed as the icon for this window.

InputContext getInputContext()

Gets the input context for this window.

<T extends EventListener> T[] getListeners(Class<T> listenerType)

Returns an array of all the objects currently registered as FooListeners upon this Window.

Locale getLocale ()

Gets the Locale object that is associated with this window, if the locale has been set.

Dialog.ModalExclusionType getModalExclusionType()

Returns the modal exclusion type of this window.

Component getMostRecentFocusOwner()

Returns the child Component of this Window that will receive the focus when this Window is focused.

Window[] getOwnedWindows()

Return an array containing all the windows this window currently owns.

Window getOwner()

Returns the owner of this window.

static Window[] getOwnerlessWindows()

Returns an array of all Windows created by this application that have no owner.

Toolkit getToolkit()

Returns the toolkit of this frame.

String getWarningString()

Gets the warning string that is displayed with this window.

WindowFocusListener[] getWindowFocusListeners()

Returns an array of all the window focus listeners registered on this window.

WindowListener[] getWindowListeners()

Returns an array of all the window listeners registered on this window.

static Window[] getWindows()

Returns an array of all Windows, both owned and ownerless, created by this application.

WindowStateListener[] getWindowStateListeners()

Returns an array of all the window state listeners registered on this window.

void hide()

Устаревшее. As of JDK version 1.5, replaced by setVisible(boolean).

boolean isActive()

Returns whether this Window is active.

boolean isAlwaysOnTop()

Returns whether this window is an always-on-top window.

boolean isAlwaysOnTopSupported()

Returns whether the always-on-top mode is supported for this window.

boolean isFocusableWindow()

Returns whether this Window can become the focused Window, that is, whether this Window or any of its subcomponents can become the focus owner.

boolean isFocusCycleRoot()

Always returns true because all Windows must be roots of a focus traversal cycle.

boolean isFocused()

Returns whether this Window is focused.

boolean isLocationByPlatform()

Returns true if this Window will appear at the default location for the native windowing system the next time this Window is made visible.

boolean isShowing()

Checks if this Window is showing on screen.

void pack()

Causes this Window to be sized to fit the preferred size and layouts of its subcomponents.

void paint(Graphics g)

Paints the container.

boolean postEvent(Event e)

Устаревшее. As of JDK version 1.1 replaced by dispatchEvent(AWTEvent).

protected void processEvent(AWTEvent e)

Processes events on this window.

protected void processWindowEvent(WindowEvent e)

Processes window events occurring on this window by dispatching them to any registered WindowListener objects.

protected void processWindowFocusEvent(WindowEvent e)

Processes window focus event occuring on this window by dispatching them to any registered WindowFocusListener objects.

protected void processWindowStateEvent(WindowEvent e)

Processes window state event occuring on this window by dispatching them to any registered WindowStateListener objects.

void removeNotify()

Makes this Container undisplayable by removing its connection to its native screen resource.

void removeWindowFocusListener(WindowFocusListener l)

Removes the specified window focus listener so that it no longer receives window events from this window.

void removeWindowListener(WindowListener l)

Removes the specified window listener so that it no longer receives window events from this window.

void removeWindowStateListener(WindowStateListener l)

Removes the specified window state listener so that it no longer receives window events from this window.

void reshape(int x, int y, int width, int height)

Устаревшее. As of JDK version 1.1, replaced by setBounds(int, int, int, int).

void setAlwaysOnTop(boolean alwaysOnTop)

Sets whether this window should always be above other windows.

void setBounds(int x, int y, int width, int height)

Moves and resizes this component.

void setBounds(Rectangle r)

Moves and resizes this component to conform to the new bounding rectangle r.

void setCursor(Cursor cursor)

Set the cursor image to a specified cursor.

void setFocusableWindowState(boolean focusableWindowState)

Sets whether this Window can become the focused Window if it meets the other requirements outlined in isFocusableWindow.

void setFocusCycleRoot(boolean focusCycleRoot)

Does nothing because Windows must always be roots of a focus traversal cycle.

void setIconImage(Image image)

Sets the image to be displayed as the icon for this window.

void setIconImages(List<? extends Image> icons)

Sets the sequence of images to be displayed as the icon for this window.

void setLocationByPlatform(boolean locationByPlatform)

Sets whether this Window should appear at the default location for the native windowing system or at the current location (returned by getLocation) the next time the Window is made visible.

void setLocationRelativeTo(Component c)

Sets the location of the window relative to the specified component.

void setMinimumSize(Dimension minimumSize)

Sets the minimum size of this window to a constant value.

void setModalExclusionType(Dialog.ModalExclusionType exclusionType)

Specifies the modal exclusion type for this window.

void setSize(Dimension d)

Resizes this component so that it has width d.width and height d.height.

void setSize(int width, int height)

Resizes this component so that it has width width and height height.

void setVisible(boolean b)

Shows or hides this Window depending on the value of parameter b.

void show()

Устаревшее. As of JDK version 1.5, replaced by setVisible(boolean).

void toBack()

If this Window is visible, sends this Window to the back and may cause it to lose focus or activation if it is the focused or active Window.

void toFront()

If this Window is visible, brings this Window to the front and may make it the focused Window.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.awt.Window

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

java.awt.Window

java.awt.Container

java.awt.Component

java.lang.Object

Window Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AwtContainerDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtContainerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;
   private Label msglabel;

   public AwtContainerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtContainerDemo  awtContainerDemo = new AwtContainerDemo();          
      awtContainerDemo.showFrameDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);
   
      msglabel = new Label();
      msglabel.setAlignment(Label.CENTER);
      msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   
   private void showWindowDemo(){
      headerLabel.setText("Container in action: Window");   
      final MessageWindow window = 
         new MessageWindow(mainFrame,
         "Welcome to TutorialsPoint AWT Tutorial.");

      Button okButton = new Button("Open a Window");
      okButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            window.setVisible(true);
            statusLabel.setText("A Window shown to the user.");                
         }
      });
      controlPanel.add(okButton);
      mainFrame.setVisible(true);  
   }

   class MessageWindow extends Window{
      private String message; 

      public MessageWindow(Frame parent, String message) { 
         super(parent);               
         this.message = message; 
         setSize(300, 300);       
         setLocationRelativeTo(parent);
         setBackground(Color.gray);
      }

      public void paint(Graphics g) { 
         super.paint(g);
         g.drawRect(0,0,getSize().width - 1,getSize().height - 1); 
         g.drawString(message,50,150); 
      } 
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtContainerDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtContainerDemo

Проверьте следующий вывод

AWT Window

Классы меню AWT

Как известно, с каждым окном верхнего уровня связана строка меню. Эта строка меню состоит из различных пунктов меню, доступных конечному пользователю. Далее каждый вариант содержит список опций, который называется выпадающим меню. Элементы управления Menu и MenuItem являются подклассом класса MenuComponent.

Меню Hiearchy

Меню AWT Hiearchy

AWT MenuComponent Class

Вступление

MenuComponent is an abstract class and is the superclass for all menu-related components.

Объявление класса

Following is the declaration for java.awt.MenuComponent class:

public abstract class MenuComponent
   extends Object
      implements Serializable

Конструкторы классов

SN Конструктор и описание
1

MenuComponent()

Creates a MenuComponent.

MenuComponent()

Creates a MenuComponent.

Методы класса

void dispatchEvent(AWTEvent e)

SN Метод и описание
1

AccessibleContext getAccessibleContext()

Gets the AccessibleContext associated with this MenuComponent.

2

Font getFont()

Gets the font used for this menu component.

3

Строка getName ()

Gets the name of the menu component.

4

MenuContainer getParent()

Returns the parent container for this menu component.

5

java.awt.peer.MenuComponentPeer getPeer()

Устаревшее. As of JDK version 1.1, programs should not directly manipulate peers.

6

protected Object getTreeLock()

Gets this component’s locking object (the object that owns the thread sychronization monitor) for AWT component-tree and layout operations.

7

protected String paramString()

Returns a string representing the state of this MenuComponent.

8

boolean postEvent(Event evt)

Устаревшее. As of JDK version 1.1, replaced by dispatchEvent.

9

protected void processEvent(AWTEvent e)

Processes events occurring on this menu component.

10

void removeNotify()

Removes the menu component’s peer.

11

void setFont(Font f)

Sets the font to be used for this menu component to the specified font.

12

void setName (String name)

Sets the name of the component to the specified string.

13

Строка toString ()

Returns a representation of this menu component as a string.

AccessibleContext getAccessibleContext()

Gets the AccessibleContext associated with this MenuComponent.

Font getFont()

Gets the font used for this menu component.

Строка getName ()

Gets the name of the menu component.

MenuContainer getParent()

Returns the parent container for this menu component.

java.awt.peer.MenuComponentPeer getPeer()

Устаревшее. As of JDK version 1.1, programs should not directly manipulate peers.

protected Object getTreeLock()

Gets this component’s locking object (the object that owns the thread sychronization monitor) for AWT component-tree and layout operations.

protected String paramString()

Returns a string representing the state of this MenuComponent.

boolean postEvent(Event evt)

Устаревшее. As of JDK version 1.1, replaced by dispatchEvent.

protected void processEvent(AWTEvent e)

Processes events occurring on this menu component.

void removeNotify()

Removes the menu component’s peer.

void setFont(Font f)

Sets the font to be used for this menu component to the specified font.

void setName (String name)

Sets the name of the component to the specified string.

Строка toString ()

Returns a representation of this menu component as a string.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.lang.Object

java.lang.Object

AWT MenuBar Class

Вступление

The MenuBar class provides menu bar bound to a frame and is platform specific.

Объявление класса

Following is the declaration for java.awt.MenuBar class:

public class MenuBar
   extends MenuComponent
      implements MenuContainer, Accessible

Конструкторы классов

SN Конструктор и описание
1

MenuBar()

Creates a new menu bar.

MenuBar()

Creates a new menu bar.

Методы класса

SN Метод и описание
1

void dispatchEvent(AWTEvent e)

2

Menu add(Menu m)

Adds the specified menu to the menu bar.

3

void addNotify()

Creates the menu bar’s peer.

4

int countMenus()

Устаревшее. As of JDK version 1.1, replaced by getMenuCount().

5

void deleteShortcut(MenuShortcut s)

Deletes the specified menu shortcut.

6

AccessibleContext getAccessibleContext()

Gets the AccessibleContext associated with this MenuBar.

7

Menu getHelpMenu()

Gets the help menu on the menu bar.

8

Menu getMenu(int i)

Gets the specified menu.

9

int getMenuCount()

Gets the number of menus on the menu bar.

10

MenuItem getShortcutMenuItem(MenuShortcut s)

Gets the instance of MenuItem associated with the specified MenuShortcut object, or null if none of the menu items being managed by this menu bar is associated with the specified menu shortcut.

11

void remove(int index)

Removes the menu located at the specified index from this menu bar.

12

void remove(MenuComponent m)

Removes the specified menu component from this menu bar.

13

void removeNotify()

Removes the menu bar’s peer.

14

void setHelpMenu(Menu m)

Sets the specified menu to be this menu bar’s help menu.

15

Enumeration shortcuts()

Gets an enumeration of all menu shortcuts this menu bar is managing.

void dispatchEvent(AWTEvent e)

Menu add(Menu m)

Adds the specified menu to the menu bar.

void addNotify()

Creates the menu bar’s peer.

int countMenus()

Устаревшее. As of JDK version 1.1, replaced by getMenuCount().

void deleteShortcut(MenuShortcut s)

Deletes the specified menu shortcut.

AccessibleContext getAccessibleContext()

Gets the AccessibleContext associated with this MenuBar.

Menu getHelpMenu()

Gets the help menu on the menu bar.

Menu getMenu(int i)

Gets the specified menu.

int getMenuCount()

Gets the number of menus on the menu bar.

MenuItem getShortcutMenuItem(MenuShortcut s)

Gets the instance of MenuItem associated with the specified MenuShortcut object, or null if none of the menu items being managed by this menu bar is associated with the specified menu shortcut.

void remove(int index)

Removes the menu located at the specified index from this menu bar.

void remove(MenuComponent m)

Removes the specified menu component from this menu bar.

void removeNotify()

Removes the menu bar’s peer.

void setHelpMenu(Menu m)

Sets the specified menu to be this menu bar’s help menu.

Enumeration shortcuts()

Gets an enumeration of all menu shortcuts this menu bar is managing.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.awt.MenuComponent

  • java.lang.Object

java.awt.MenuComponent

java.lang.Object

MenuBar Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AWTMenuDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AWTMenuDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AWTMenuDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AWTMenuDemo  awtMenuDemo = new AWTMenuDemo();     
      awtMenuDemo.showMenuDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showMenuDemo(){
      //create a menu bar
      final MenuBar menuBar = new MenuBar();

      //create menus
      Menu fileMenu = new Menu("File");
      Menu editMenu = new Menu("Edit"); 
      final Menu aboutMenu = new Menu("About");

      //create menu items
      MenuItem newMenuItem = 
         new MenuItem("New",new MenuShortcut(KeyEvent.VK_N));
      newMenuItem.setActionCommand("New");

      MenuItem openMenuItem = new MenuItem("Open");
      openMenuItem.setActionCommand("Open");

      MenuItem saveMenuItem = new MenuItem("Save");
      saveMenuItem.setActionCommand("Save");

      MenuItem exitMenuItem = new MenuItem("Exit");
      exitMenuItem.setActionCommand("Exit");

      MenuItem cutMenuItem = new MenuItem("Cut");
      cutMenuItem.setActionCommand("Cut");

      MenuItem copyMenuItem = new MenuItem("Copy");
      copyMenuItem.setActionCommand("Copy");

      MenuItem pasteMenuItem = new MenuItem("Paste");
      pasteMenuItem.setActionCommand("Paste");
   
      MenuItemListener menuItemListener = new MenuItemListener();

      newMenuItem.addActionListener(menuItemListener);
      openMenuItem.addActionListener(menuItemListener);
      saveMenuItem.addActionListener(menuItemListener);
      exitMenuItem.addActionListener(menuItemListener);
      cutMenuItem.addActionListener(menuItemListener);
      copyMenuItem.addActionListener(menuItemListener);
      pasteMenuItem.addActionListener(menuItemListener);

      final CheckboxMenuItem showWindowMenu = 
         new CheckboxMenuItem("Show About", true);
      showWindowMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            if(showWindowMenu.getState()){
               menuBar.add(aboutMenu);
            }else{
               menuBar.remove(aboutMenu);
            }
         }
      });

      //add menu items to menus
      fileMenu.add(newMenuItem);
      fileMenu.add(openMenuItem);
      fileMenu.add(saveMenuItem);
      fileMenu.addSeparator();
      fileMenu.add(showWindowMenu);
      fileMenu.addSeparator();
      fileMenu.add(exitMenuItem);

      editMenu.add(cutMenuItem);
      editMenu.add(copyMenuItem);
      editMenu.add(pasteMenuItem);

      //add menu to menubar
      menuBar.add(fileMenu);
      menuBar.add(editMenu);
      menuBar.add(aboutMenu);

      //add menubar to the frame
      mainFrame.setMenuBar(menuBar);
      mainFrame.setVisible(true);  
   }

   class MenuItemListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {            
         statusLabel.setText(e.getActionCommand() 
            + " MenuItem clicked.");
      }    
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AWTMenuDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AWTMenuDemo

Проверьте следующий вывод

AWT MenuBar

AWT MenuItem Class

Вступление

The MenuBar class represents the actual item in a menu. All items in a menu should derive from class MenuItem, or one of its subclasses. By default, it embodies a simple labeled menu item.

Объявление класса

Following is the declaration for java.awt.MenuItem class:

public class MenuItem
   extends MenuComponent
      implements Accessible

Конструкторы классов

SN Конструктор и описание
1

MenuItem()

Constructs a new MenuItem with an empty label and no keyboard shortcut.

2

MenuItem(String label)

Constructs a new MenuItem with the specified label and no keyboard shortcut.

3

MenuItem(String label, MenuShortcut s)

Create a menu item with an associated keyboard shortcut.

MenuItem()

Constructs a new MenuItem with an empty label and no keyboard shortcut.

MenuItem(String label)

Constructs a new MenuItem with the specified label and no keyboard shortcut.

MenuItem(String label, MenuShortcut s)

Create a menu item with an associated keyboard shortcut.

Методы класса

SN Метод и описание
1

void addActionListener(ActionListener l)

Adds the specified action listener to receive action events from this menu item.

2

void addNotify()

Creates the menu item’s peer.

3

void deleteShortcut()

Delete any MenuShortcut object associated with this menu item.

4

void disable()

Устаревшее. As of JDK version 1.1, replaced by setEnabled(boolean).

5

protected void disableEvents(long eventsToDisable)

Disables event delivery to this menu item for events defined by the specified event mask parameter.

6

void enable()

Устаревшее. As of JDK version 1.1, replaced by setEnabled(boolean).

7

void enable(boolean b)

Устаревшее. As of JDK version 1.1, replaced by setEnabled(boolean).

8

protected void enableEvents(long eventsToEnable)

Enables event delivery to this menu item for events to be defined by the specified event mask parameter.

9

AccessibleContext getAccessibleContext()

Gets the AccessibleContext associated with this MenuItem.

10

String getActionCommand()

Gets the command name of the action event that is fired by this menu item.

11

ActionListener[] getActionListeners()

Returns an array of all the action listeners registered on this menu item.

12

String getLabel()

Gets the label for this menu item.

13

EventListener[] getListeners(Class listenerType)

Returns an array of all the objects currently registered as FooListeners upon this MenuItem.

14

MenuShortcut getShortcut()

Get the MenuShortcut object associated with this menu item.

15

boolean isEnabled()

Checks whether this menu item is enabled.

16

String paramString()

Returns a string representing the state of this MenuItem.

17

protected void processActionEvent(ActionEvent e)

Processes action events occurring on this menu item, by dispatching them to any registered ActionListener objects.

18

protected void processEvent(AWTEvent e)

Processes events on this menu item.

19

void removeActionListener(ActionListener l)

Removes the specified action listener so it no longer receives action events from this menu item.

20

void setActionCommand(String command)

Sets the command name of the action event that is fired by this menu item.

21

void setEnabled(boolean b)

Sets whether or not this menu item can be chosen.

22

void setLabel(String label)

Sets the label for this menu item to the specified label.

23

void setShortcut(MenuShortcut s)

Set the MenuShortcut object associated with this menu item.

void addActionListener(ActionListener l)

Adds the specified action listener to receive action events from this menu item.

void addNotify()

Creates the menu item’s peer.

void deleteShortcut()

Delete any MenuShortcut object associated with this menu item.

void disable()

Устаревшее. As of JDK version 1.1, replaced by setEnabled(boolean).

protected void disableEvents(long eventsToDisable)

Disables event delivery to this menu item for events defined by the specified event mask parameter.

void enable()

Устаревшее. As of JDK version 1.1, replaced by setEnabled(boolean).

void enable(boolean b)

Устаревшее. As of JDK version 1.1, replaced by setEnabled(boolean).

protected void enableEvents(long eventsToEnable)

Enables event delivery to this menu item for events to be defined by the specified event mask parameter.

AccessibleContext getAccessibleContext()

Gets the AccessibleContext associated with this MenuItem.

String getActionCommand()

Gets the command name of the action event that is fired by this menu item.

ActionListener[] getActionListeners()

Returns an array of all the action listeners registered on this menu item.

String getLabel()

Gets the label for this menu item.

EventListener[] getListeners(Class listenerType)

Returns an array of all the objects currently registered as FooListeners upon this MenuItem.

MenuShortcut getShortcut()

Get the MenuShortcut object associated with this menu item.

boolean isEnabled()

Checks whether this menu item is enabled.

String paramString()

Returns a string representing the state of this MenuItem.

protected void processActionEvent(ActionEvent e)

Processes action events occurring on this menu item, by dispatching them to any registered ActionListener objects.

protected void processEvent(AWTEvent e)

Processes events on this menu item.

void removeActionListener(ActionListener l)

Removes the specified action listener so it no longer receives action events from this menu item.

void setActionCommand(String command)

Sets the command name of the action event that is fired by this menu item.

void setEnabled(boolean b)

Sets whether or not this menu item can be chosen.

void setLabel(String label)

Sets the label for this menu item to the specified label.

void setShortcut(MenuShortcut s)

Set the MenuShortcut object associated with this menu item.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.awt.MenuComponent

  • java.lang.Object

java.awt.MenuComponent

java.lang.Object

MenuItem Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AWTMenuDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AWTMenuDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AWTMenuDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AWTMenuDemo  awtMenuDemo = new AWTMenuDemo();     
      awtMenuDemo.showMenuDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showMenuDemo(){
      //create a menu bar
      final MenuBar menuBar = new MenuBar();

      //create menus
      Menu fileMenu = new Menu("File");
      Menu editMenu = new Menu("Edit"); 
      final Menu aboutMenu = new Menu("About");

      //create menu items
      MenuItem newMenuItem = 
         new MenuItem("New",new MenuShortcut(KeyEvent.VK_N));
      newMenuItem.setActionCommand("New");

      MenuItem openMenuItem = new MenuItem("Open");
      openMenuItem.setActionCommand("Open");

      MenuItem saveMenuItem = new MenuItem("Save");
      saveMenuItem.setActionCommand("Save");

      MenuItem exitMenuItem = new MenuItem("Exit");
      exitMenuItem.setActionCommand("Exit");

      MenuItem cutMenuItem = new MenuItem("Cut");
      cutMenuItem.setActionCommand("Cut");

      MenuItem copyMenuItem = new MenuItem("Copy");
      copyMenuItem.setActionCommand("Copy");

      MenuItem pasteMenuItem = new MenuItem("Paste");
      pasteMenuItem.setActionCommand("Paste");
   
      MenuItemListener menuItemListener = new MenuItemListener();

      newMenuItem.addActionListener(menuItemListener);
      openMenuItem.addActionListener(menuItemListener);
      saveMenuItem.addActionListener(menuItemListener);
      exitMenuItem.addActionListener(menuItemListener);
      cutMenuItem.addActionListener(menuItemListener);
      copyMenuItem.addActionListener(menuItemListener);
      pasteMenuItem.addActionListener(menuItemListener);

      final CheckboxMenuItem showWindowMenu = 
         new CheckboxMenuItem("Show About", true);
      showWindowMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            if(showWindowMenu.getState()){
               menuBar.add(aboutMenu);
            }else{
               menuBar.remove(aboutMenu);
            }
         }
      });

      //add menu items to menus
      fileMenu.add(newMenuItem);
      fileMenu.add(openMenuItem);
      fileMenu.add(saveMenuItem);
      fileMenu.addSeparator();
      fileMenu.add(showWindowMenu);
      fileMenu.addSeparator();
      fileMenu.add(exitMenuItem);

      editMenu.add(cutMenuItem);
      editMenu.add(copyMenuItem);
      editMenu.add(pasteMenuItem);

      //add menu to menubar
      menuBar.add(fileMenu);
      menuBar.add(editMenu);
      menuBar.add(aboutMenu);

      //add menubar to the frame
      mainFrame.setMenuBar(menuBar);
      mainFrame.setVisible(true);  
   }

   class MenuItemListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {            
         statusLabel.setText(e.getActionCommand() 
            + " MenuItem clicked.");
      }    
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AWTMenuDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AWTMenuDemo

Проверьте следующий вывод. (Click on File Menu. Select any menu item.)

AWT MenuItem

AWT Menu Class

Вступление

The Menu class represents pull-down menu component which is deployed from a menu bar.

Объявление класса

Following is the declaration for java.awt.Menu class:

public class Menu
   extends MenuItem
      implements MenuContainer, Accessible

Конструкторы классов

SN Конструктор и описание
1

Menu()

Constructs a new menu with an empty label.

2

Menu(String label)

Constructs a new menu with the specified label.

3

Menu(String label, boolean tearOff)

Constructs a new menu with the specified label, indicating whether the menu can be torn off.

Menu()

Constructs a new menu with an empty label.

Menu(String label)

Constructs a new menu with the specified label.

Menu(String label, boolean tearOff)

Constructs a new menu with the specified label, indicating whether the menu can be torn off.

Методы класса

SN Метод и описание
1

MenuItem add(MenuItem mi)

Adds the specified menu item to this menu.

2

void add(String label)

Adds an item with the specified label to this menu.

3

void addNotify()

Creates the menu’s peer.

4

void addSeparator()

Adds a separator line, or a hypen, to the menu at the current position.

5

int countItems()

Устаревшее. As of JDK version 1.1, replaced by getItemCount().

6

AccessibleContext getAccessibleContext()

Gets the AccessibleContext associated with this Menu.

7

MenuItem getItem(int index)

Gets the item located at the specified index of this menu.

8

int getItemCount()

Get the number of items in this menu.

9

void insert(MenuItem menuitem, int index)

Inserts a menu item into this menu at the specified position.

10

void insert(String label, int index)

Inserts a menu item with the specified label into this menu at the specified position.

11

void insertSeparator(int index)

Inserts a separator at the specified position.

12

boolean isTearOff()

Indicates whether this menu is a tear-off menu.

13

String paramString()

Returns a string representing the state of this Menu.

14

void remove(int index)

Removes the menu item at the specified index from this menu.

15

void remove(MenuComponent item)

Removes the specified menu item from this menu.

16

void removeAll()

Removes all items from this menu.

17

void removeNotify()

Removes the menu’s peer.

MenuItem add(MenuItem mi)

Adds the specified menu item to this menu.

void add(String label)

Adds an item with the specified label to this menu.

void addNotify()

Creates the menu’s peer.

void addSeparator()

Adds a separator line, or a hypen, to the menu at the current position.

int countItems()

Устаревшее. As of JDK version 1.1, replaced by getItemCount().

AccessibleContext getAccessibleContext()

Gets the AccessibleContext associated with this Menu.

MenuItem getItem(int index)

Gets the item located at the specified index of this menu.

int getItemCount()

Get the number of items in this menu.

void insert(MenuItem menuitem, int index)

Inserts a menu item into this menu at the specified position.

void insert(String label, int index)

Inserts a menu item with the specified label into this menu at the specified position.

void insertSeparator(int index)

Inserts a separator at the specified position.

boolean isTearOff()

Indicates whether this menu is a tear-off menu.

String paramString()

Returns a string representing the state of this Menu.

void remove(int index)

Removes the menu item at the specified index from this menu.

void remove(MenuComponent item)

Removes the specified menu item from this menu.

void removeAll()

Removes all items from this menu.

void removeNotify()

Removes the menu’s peer.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.awt.MenuItem

  • java.awt.MenuComponent

  • java.lang.Object

java.awt.MenuItem

java.awt.MenuComponent

java.lang.Object

Menu Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AWTMenuDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AWTMenuDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AWTMenuDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AWTMenuDemo  awtMenuDemo = new AWTMenuDemo();     
      awtMenuDemo.showMenuDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showMenuDemo(){
      //create a menu bar
      final MenuBar menuBar = new MenuBar();

      //create menus
      Menu fileMenu = new Menu("File");
      Menu editMenu = new Menu("Edit"); 
      final Menu aboutMenu = new Menu("About");

      //create menu items
      MenuItem newMenuItem = 
         new MenuItem("New",new MenuShortcut(KeyEvent.VK_N));
      newMenuItem.setActionCommand("New");

      MenuItem openMenuItem = new MenuItem("Open");
      openMenuItem.setActionCommand("Open");

      MenuItem saveMenuItem = new MenuItem("Save");
      saveMenuItem.setActionCommand("Save");

      MenuItem exitMenuItem = new MenuItem("Exit");
      exitMenuItem.setActionCommand("Exit");

      MenuItem cutMenuItem = new MenuItem("Cut");
      cutMenuItem.setActionCommand("Cut");

      MenuItem copyMenuItem = new MenuItem("Copy");
      copyMenuItem.setActionCommand("Copy");

      MenuItem pasteMenuItem = new MenuItem("Paste");
      pasteMenuItem.setActionCommand("Paste");
   
      MenuItemListener menuItemListener = new MenuItemListener();

      newMenuItem.addActionListener(menuItemListener);
      openMenuItem.addActionListener(menuItemListener);
      saveMenuItem.addActionListener(menuItemListener);
      exitMenuItem.addActionListener(menuItemListener);
      cutMenuItem.addActionListener(menuItemListener);
      copyMenuItem.addActionListener(menuItemListener);
      pasteMenuItem.addActionListener(menuItemListener);

      final CheckboxMenuItem showWindowMenu = 
         new CheckboxMenuItem("Show About", true);
      showWindowMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            if(showWindowMenu.getState()){
               menuBar.add(aboutMenu);
            }else{
               menuBar.remove(aboutMenu);
            }
         }
      });

      //add menu items to menus
      fileMenu.add(newMenuItem);
      fileMenu.add(openMenuItem);
      fileMenu.add(saveMenuItem);
      fileMenu.addSeparator();
      fileMenu.add(showWindowMenu);
      fileMenu.addSeparator();
      fileMenu.add(exitMenuItem);

      editMenu.add(cutMenuItem);
      editMenu.add(copyMenuItem);
      editMenu.add(pasteMenuItem);

      //add menu to menubar
      menuBar.add(fileMenu);
      menuBar.add(editMenu);
      menuBar.add(aboutMenu);

      //add menubar to the frame
      mainFrame.setMenuBar(menuBar);
      mainFrame.setVisible(true);  
   }

   class MenuItemListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {            
         statusLabel.setText(e.getActionCommand() 
            + " MenuItem clicked.");
      }    
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AWTMenuDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AWTMenuDemo

Проверьте следующий вывод. (Click on File Menu.)

AWT Menu

AWT CheckboxMenuItem Class

Вступление

The CheckboxMenuItem class represents a check box which can be included in a menu. Selecting the check box in the menu changes control’s state from on to off or from off to on .

Объявление класса

Following is the declaration for java.awt.CheckboxMenuItem class:

public class CheckboxMenuItem
   extends MenuItem
      implements ItemSelectable, Accessible

Конструкторы классов

SN Конструктор и описание
1

CheckboxMenuItem()

Create a check box menu item with an empty label.

2

CheckboxMenuItem(String label)

Create a check box menu item with the specified label.

3

CheckboxMenuItem(String label, boolean state)

Create a check box menu item with the specified label and state.

CheckboxMenuItem()

Create a check box menu item with an empty label.

CheckboxMenuItem(String label)

Create a check box menu item with the specified label.

CheckboxMenuItem(String label, boolean state)

Create a check box menu item with the specified label and state.

Методы класса

SN Метод и описание
1

void addItemListener(ItemListener l)

Adds the specified item listener to receive item events from this check box menu item.

2

void addNotify()

Creates the peer of the checkbox item.

3

AccessibleContext getAccessibleContext()

Gets the AccessibleContext associated with this CheckboxMenuItem.

4

ItemListener[] getItemListeners()

Returns an array of all the item listeners registered on this checkbox menuitem.

5

<T extends EventListener> T[] getListeners(Class<T> listenerType)

Returns an array of all the objects currently registered as FooListeners upon this CheckboxMenuItem.

6

Object[] getSelectedObjects()

Returns the an array (length 1) containing the checkbox menu item label or null if the checkbox is not selected.

7

boolean getState()

Determines whether the state of this check box menu item is “on” or “off.”

8

String paramString()

Returns a string representing the state of this CheckBoxMenuItem.

9

protected void processEvent(AWTEvent e)

Processes events on this check box menu item.

10

protected void processItemEvent(ItemEvent e)

Processes item events occurring on this check box menu item by dispatching them to any registered ItemListener objects.

11

void removeItemListener(ItemListener l)

Removes the specified item listener so that it no longer receives item events from this check box menu item.

12

void setState(boolean b)

Sets this check box menu item to the specifed state.

void addItemListener(ItemListener l)

Adds the specified item listener to receive item events from this check box menu item.

void addNotify()

Creates the peer of the checkbox item.

AccessibleContext getAccessibleContext()

Gets the AccessibleContext associated with this CheckboxMenuItem.

ItemListener[] getItemListeners()

Returns an array of all the item listeners registered on this checkbox menuitem.

<T extends EventListener> T[] getListeners(Class<T> listenerType)

Returns an array of all the objects currently registered as FooListeners upon this CheckboxMenuItem.

Object[] getSelectedObjects()

Returns the an array (length 1) containing the checkbox menu item label or null if the checkbox is not selected.

boolean getState()

Determines whether the state of this check box menu item is “on” or “off.”

String paramString()

Returns a string representing the state of this CheckBoxMenuItem.

protected void processEvent(AWTEvent e)

Processes events on this check box menu item.

protected void processItemEvent(ItemEvent e)

Processes item events occurring on this check box menu item by dispatching them to any registered ItemListener objects.

void removeItemListener(ItemListener l)

Removes the specified item listener so that it no longer receives item events from this check box menu item.

void setState(boolean b)

Sets this check box menu item to the specifed state.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.awt.MenuItem

  • java.awt.MenuComponent

  • java.lang.Object

java.awt.MenuItem

java.awt.MenuComponent

java.lang.Object

CheckboxMenuItem Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AWTMenuDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AWTMenuDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AWTMenuDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AWTMenuDemo  awtMenuDemo = new AWTMenuDemo();     
      awtMenuDemo.showMenuDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showMenuDemo(){
      //create a menu bar
      final MenuBar menuBar = new MenuBar();

      //create menus
      Menu fileMenu = new Menu("File");
      Menu editMenu = new Menu("Edit"); 
      final Menu aboutMenu = new Menu("About");

      //create menu items
      MenuItem newMenuItem = 
         new MenuItem("New",new MenuShortcut(KeyEvent.VK_N));
      newMenuItem.setActionCommand("New");

      MenuItem openMenuItem = new MenuItem("Open");
      openMenuItem.setActionCommand("Open");

      MenuItem saveMenuItem = new MenuItem("Save");
      saveMenuItem.setActionCommand("Save");

      MenuItem exitMenuItem = new MenuItem("Exit");
      exitMenuItem.setActionCommand("Exit");

      MenuItem cutMenuItem = new MenuItem("Cut");
      cutMenuItem.setActionCommand("Cut");

      MenuItem copyMenuItem = new MenuItem("Copy");
      copyMenuItem.setActionCommand("Copy");

      MenuItem pasteMenuItem = new MenuItem("Paste");
      pasteMenuItem.setActionCommand("Paste");
   
      MenuItemListener menuItemListener = new MenuItemListener();

      newMenuItem.addActionListener(menuItemListener);
      openMenuItem.addActionListener(menuItemListener);
      saveMenuItem.addActionListener(menuItemListener);
      exitMenuItem.addActionListener(menuItemListener);
      cutMenuItem.addActionListener(menuItemListener);
      copyMenuItem.addActionListener(menuItemListener);
      pasteMenuItem.addActionListener(menuItemListener);

      final CheckboxMenuItem showWindowMenu = 
         new CheckboxMenuItem("Show About", true);
      showWindowMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            if(showWindowMenu.getState()){
               menuBar.add(aboutMenu);
            }else{
               menuBar.remove(aboutMenu);
            }
         }
      });

      //add menu items to menus
      fileMenu.add(newMenuItem);
      fileMenu.add(openMenuItem);
      fileMenu.add(saveMenuItem);
      fileMenu.addSeparator();
      fileMenu.add(showWindowMenu);
      fileMenu.addSeparator();
      fileMenu.add(exitMenuItem);

      editMenu.add(cutMenuItem);
      editMenu.add(copyMenuItem);
      editMenu.add(pasteMenuItem);

      //add menu to menubar
      menuBar.add(fileMenu);
      menuBar.add(editMenu);
      menuBar.add(aboutMenu);

      //add menubar to the frame
      mainFrame.setMenuBar(menuBar);
      mainFrame.setVisible(true);  
   }

   class MenuItemListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {            
         statusLabel.setText(e.getActionCommand() 
            + " MenuItem clicked.");
      }    
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AWTMenuDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AWTMenuDemo

Проверьте следующий вывод. (Click on File Menu. Unselect “Show About” menu item.)

AWT CheckboxMenuItem

AWT PopupMenu Class

Вступление

Popup menu represents a menu which can be dynamically popped up at a specified position within a component.

Объявление класса

Following is the declaration for java.awt.PopupMenu class:

public class CheckboxMenuItem
   extends MenuItem
      implements ItemSelectable, Accessible

Конструкторы классов

SN Конструктор и описание
1

PopupMenu()

Creates a new popup menu with an empty name.

2

PopupMenu(String label)

Creates a new popup menu with the specified name.

PopupMenu()

Creates a new popup menu with an empty name.

PopupMenu(String label)

Creates a new popup menu with the specified name.

Методы класса

SN Метод и описание
1

void addNotify()

Creates the popup menu’s peer.

2

AccessibleContext getAccessibleContext()

Gets the AccessibleContext associated with this PopupMenu.

3

MenuContainer getParent()

Returns the parent container for this menu component.

4

void show(Component origin, int x, int y)

Shows the popup menu at the x, y position relative to an origin component.

void addNotify()

Creates the popup menu’s peer.

AccessibleContext getAccessibleContext()

Gets the AccessibleContext associated with this PopupMenu.

MenuContainer getParent()

Returns the parent container for this menu component.

void show(Component origin, int x, int y)

Shows the popup menu at the x, y position relative to an origin component.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.awt.MenuItem

  • java.awt.MenuComponent

  • java.lang.Object

java.awt.MenuItem

java.awt.MenuComponent

java.lang.Object

PopupMenu Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AWTMenuDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AWTMenuDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AWTMenuDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AWTMenuDemo  awtMenuDemo = new AWTMenuDemo();     
      awtMenuDemo.showPopupMenuDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showPopupMenuDemo(){
      final PopupMenu editMenu = new PopupMenu("Edit"); 

      MenuItem cutMenuItem = new MenuItem("Cut");
      cutMenuItem.setActionCommand("Cut");

      MenuItem copyMenuItem = new MenuItem("Copy");
      copyMenuItem.setActionCommand("Copy");

      MenuItem pasteMenuItem = new MenuItem("Paste");
      pasteMenuItem.setActionCommand("Paste");

      MenuItemListener menuItemListener = new MenuItemListener();

      cutMenuItem.addActionListener(menuItemListener);
      copyMenuItem.addActionListener(menuItemListener);
      pasteMenuItem.addActionListener(menuItemListener);

      editMenu.add(cutMenuItem);
      editMenu.add(copyMenuItem);
      editMenu.add(pasteMenuItem);   
      
      controlPanel.addMouseListener(new MouseAdapter() {
         public void mouseClicked(MouseEvent e) {            
               editMenu.show(controlPanel, e.getX(), e.getY());
         }               
      });
      controlPanel.add(editMenu); 

      mainFrame.setVisible(true);
   }
	
   class MenuItemListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {            
         statusLabel.setText(e.getActionCommand() 
            + " MenuItem clicked.");
      }    
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AWTMenuDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AWTMenuDemo

Проверьте следующий вывод. (Click in the middle on the screen.)

AWT PopupMenu

Графические классы AWT

Графические элементы управления позволяют приложению рисовать на компоненте или на изображении.

AWT Graphics Class

Вступление

The Graphics class is the abstract super class for all graphics contexts which allow an application to draw onto components that can be realized on various devices, or onto off-screen images as well.

A Graphics object encapsulates all state information required for the basic rendering operations that Java supports. State information includes the following properties.

  • The Component object on which to draw.

  • A translation origin for rendering and clipping coordinates.

  • The current clip.

  • The current color.

  • The current font.

  • The current logical pixel operation function.

  • The current XOR alternation color

The Component object on which to draw.

A translation origin for rendering and clipping coordinates.

The current clip.

The current color.

The current font.

The current logical pixel operation function.

The current XOR alternation color

Объявление класса

Following is the declaration for java.awt.Graphics class:

public abstract class Graphics
   extends Object

Конструкторы классов

SN Конструктор и описание
1

Graphics() ()

Constructs a new Graphics object.

Graphics() ()

Constructs a new Graphics object.

Методы класса

SN Метод и описание
1

abstract void clearRect(int x, int y, int width, int height)

Clears the specified rectangle by filling it with the background color of the current drawing surface.

2

abstract void clipRect(int x, int y, int width, int height)

Intersects the current clip with the specified rectangle.

3

abstract void copyArea(int x, int y, int width, int height, int dx, int dy)

Copies an area of the component by a distance specified by dx and dy.

4

abstract Graphics create()

Creates a new Graphics object that is a copy of this Graphics object.

5

Graphics create(int x, int y, int width, int height)

Creates a new Graphics object based on this Graphics object, but with a new translation and clip area.

6

abstract void dispose()

Disposes of this graphics context and releases any system resources that it is using.

7

void draw3DRect(int x, int y, int width, int height, boolean raised)

Draws a 3-D highlighted outline of the specified rectangle.

8

abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle)

Draws the outline of a circular or elliptical arc covering the specified rectangle.

9

void drawBytes(byte[] data, int offset, int length, int x, int y)

Draws the text given by the specified byte array, using this graphics context’s current font and color.

10

void drawChars(char[] data, int offset, int length, int x, int y)

Draws the text given by the specified character array, using this graphics context’s current font and color.

11

abstract boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer)

Draws as much of the specified image as is currently available.

12

abstract boolean drawImage(Image img, int x, int y, ImageObserver observer)

Draws as much of the specified image as is currently available.

13

abstract boolean drawImage(Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer)

Draws as much of the specified image as has already been scaled to fit inside the specified rectangle.

14

abstract boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer)

Draws as much of the specified image as has already been scaled to fit inside the specified rectangle.

15

abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Color bgcolor, ImageObserver observer)

Draws as much of the specified area of the specified image as is currently available, scaling it on the fly to fit inside the specified area of the destination drawable surface.

16

abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer)

Draws as much of the specified area of the specified image as is currently available, scaling it on the fly to fit inside the specified area of the destination drawable surface.

17

abstract void drawLine(int x1, int y1, int x2, int y2)

Draws a line, using the current color, between the points (x1, y1) and (x2, y2) in this graphics context’s coordinate system.

18

abstract void drawOval(int x, int y, int width, int height)

Draws the outline of an oval.

19

abstract void drawPolygon(int[] xPoints, int[] yPoints, int nPoints)

Draws a closed polygon defined by arrays of x and y coordinates.

20

void drawPolygon(Polygon p)

Draws the outline of a polygon defined by the specified Polygon object.

21

abstract void drawPolyline(int[] xPoints, int[] yPoints, int nPoints)

Draws a sequence of connected lines defined by arrays of x and y coordinates.

22

void drawRect(int x, int y, int width, int height)

Draws the outline of the specified rectangle.

23

abstract void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight)

Draws an outlined round-cornered rectangle using this graphics context’s current color.

24

abstract void drawString(AttributedCharacterIterator iterator, int x, int y)

Renders the text of the specified iterator applying its attributes in accordance with the specification of the TextAttribute class.

25

abstract void drawString(String str, int x, int y)

Draws the text given by the specified string, using this graphics context’s current font and color.

26

void fill3DRect(int x, int y, int width, int height, boolean raised)

Paints a 3-D highlighted rectangle filled with the current color.

27

abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle)

Fills a circular or elliptical arc covering the specified rectangle.

28

abstract void fillOval(int x, int y, int width, int height)

Fills an oval bounded by the specified rectangle with the current color.

29

abstract void fillPolygon(int[] xPoints, int[] yPoints, int nPoints)

Fills a closed polygon defined by arrays of x and y coordinates.

30

void fillPolygon(Polygon p)

Fills the polygon defined by the specified Polygon object with the graphics context’s current color.

31

abstract void fillRect(int x, int y, int width, int height)

Fills the specified rectangle.

32

abstract void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight)

Fills the specified rounded corner rectangle with the current color.

33

void finalize()

Disposes of this graphics context once it is no longer referenced.

34

abstract Shape getClip()

Gets the current clipping area.

35

abstract Rectangle getClipBounds()

Returns the bounding rectangle of the current clipping area.

36

Rectangle getClipBounds(Rectangle r)

Returns the bounding rectangle of the current clipping area.

37

Rectangle getClipRect()

Устаревшее. As of JDK version 1.1, replaced by getClipBounds().

38

abstract Color getColor()

Gets this graphics context’s current color.

39

abstract Font getFont()

Gets the current font.

40

FontMetrics getFontMetrics()

Gets the font metrics of the current font.

41

abstract FontMetrics getFontMetrics(Font f)

Gets the font metrics for the specified font.

42

boolean hitClip(int x, int y, int width, int height)

Returns true if the specified rectangular area might intersect the current clipping area.

43

abstract void setClip(int x, int y, int width, int height)

Sets the current clip to the rectangle specified by the given coordinates.

44

abstract void setClip(Shape clip)

Sets the current clipping area to an arbitrary clip shape.

45

abstract void setColor(Color c)

Sets this graphics context’s current color to the specified color.

46

abstract void setFont(Font font)

Sets this graphics context’s font to the specified font.

47

abstract void setPaintMode()

Sets the paint mode of this graphics context to overwrite the destination with this graphics context’s current color.

48

abstract void setXORMode(Color c1)

Sets the paint mode of this graphics context to alternate between this graphics context’s current color and the new specified color.

49

Строка toString ()

Returns a String object representing this Graphics object’s value.

50

abstract void translate(int x, int y)

Translates the origin of the graphics context to the point (x, y) in the current coordinate system.

abstract void clearRect(int x, int y, int width, int height)

Clears the specified rectangle by filling it with the background color of the current drawing surface.

abstract void clipRect(int x, int y, int width, int height)

Intersects the current clip with the specified rectangle.

abstract void copyArea(int x, int y, int width, int height, int dx, int dy)

Copies an area of the component by a distance specified by dx and dy.

abstract Graphics create()

Creates a new Graphics object that is a copy of this Graphics object.

Graphics create(int x, int y, int width, int height)

Creates a new Graphics object based on this Graphics object, but with a new translation and clip area.

abstract void dispose()

Disposes of this graphics context and releases any system resources that it is using.

void draw3DRect(int x, int y, int width, int height, boolean raised)

Draws a 3-D highlighted outline of the specified rectangle.

abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle)

Draws the outline of a circular or elliptical arc covering the specified rectangle.

void drawBytes(byte[] data, int offset, int length, int x, int y)

Draws the text given by the specified byte array, using this graphics context’s current font and color.

void drawChars(char[] data, int offset, int length, int x, int y)

Draws the text given by the specified character array, using this graphics context’s current font and color.

abstract boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer)

Draws as much of the specified image as is currently available.

abstract boolean drawImage(Image img, int x, int y, ImageObserver observer)

Draws as much of the specified image as is currently available.

abstract boolean drawImage(Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer)

Draws as much of the specified image as has already been scaled to fit inside the specified rectangle.

abstract boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer)

Draws as much of the specified image as has already been scaled to fit inside the specified rectangle.

abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Color bgcolor, ImageObserver observer)

Draws as much of the specified area of the specified image as is currently available, scaling it on the fly to fit inside the specified area of the destination drawable surface.

abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer)

Draws as much of the specified area of the specified image as is currently available, scaling it on the fly to fit inside the specified area of the destination drawable surface.

abstract void drawLine(int x1, int y1, int x2, int y2)

Draws a line, using the current color, between the points (x1, y1) and (x2, y2) in this graphics context’s coordinate system.

abstract void drawOval(int x, int y, int width, int height)

Draws the outline of an oval.

abstract void drawPolygon(int[] xPoints, int[] yPoints, int nPoints)

Draws a closed polygon defined by arrays of x and y coordinates.

void drawPolygon(Polygon p)

Draws the outline of a polygon defined by the specified Polygon object.

abstract void drawPolyline(int[] xPoints, int[] yPoints, int nPoints)

Draws a sequence of connected lines defined by arrays of x and y coordinates.

void drawRect(int x, int y, int width, int height)

Draws the outline of the specified rectangle.

abstract void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight)

Draws an outlined round-cornered rectangle using this graphics context’s current color.

abstract void drawString(AttributedCharacterIterator iterator, int x, int y)

Renders the text of the specified iterator applying its attributes in accordance with the specification of the TextAttribute class.

abstract void drawString(String str, int x, int y)

Draws the text given by the specified string, using this graphics context’s current font and color.

void fill3DRect(int x, int y, int width, int height, boolean raised)

Paints a 3-D highlighted rectangle filled with the current color.

abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle)

Fills a circular or elliptical arc covering the specified rectangle.

abstract void fillOval(int x, int y, int width, int height)

Fills an oval bounded by the specified rectangle with the current color.

abstract void fillPolygon(int[] xPoints, int[] yPoints, int nPoints)

Fills a closed polygon defined by arrays of x and y coordinates.

void fillPolygon(Polygon p)

Fills the polygon defined by the specified Polygon object with the graphics context’s current color.

abstract void fillRect(int x, int y, int width, int height)

Fills the specified rectangle.

abstract void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight)

Fills the specified rounded corner rectangle with the current color.

void finalize()

Disposes of this graphics context once it is no longer referenced.

abstract Shape getClip()

Gets the current clipping area.

abstract Rectangle getClipBounds()

Returns the bounding rectangle of the current clipping area.

Rectangle getClipBounds(Rectangle r)

Returns the bounding rectangle of the current clipping area.

Rectangle getClipRect()

Устаревшее. As of JDK version 1.1, replaced by getClipBounds().

abstract Color getColor()

Gets this graphics context’s current color.

abstract Font getFont()

Gets the current font.

FontMetrics getFontMetrics()

Gets the font metrics of the current font.

abstract FontMetrics getFontMetrics(Font f)

Gets the font metrics for the specified font.

boolean hitClip(int x, int y, int width, int height)

Returns true if the specified rectangular area might intersect the current clipping area.

abstract void setClip(int x, int y, int width, int height)

Sets the current clip to the rectangle specified by the given coordinates.

abstract void setClip(Shape clip)

Sets the current clipping area to an arbitrary clip shape.

abstract void setColor(Color c)

Sets this graphics context’s current color to the specified color.

abstract void setFont(Font font)

Sets this graphics context’s font to the specified font.

abstract void setPaintMode()

Sets the paint mode of this graphics context to overwrite the destination with this graphics context’s current color.

abstract void setXORMode(Color c1)

Sets the paint mode of this graphics context to alternate between this graphics context’s current color and the new specified color.

Строка toString ()

Returns a String object representing this Graphics object’s value.

abstract void translate(int x, int y)

Translates the origin of the graphics context to the point (x, y) in the current coordinate system.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.lang.Object

java.lang.Object

Graphics Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AWTGraphicsDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

public class AWTGraphicsDemo extends Frame {
       
   public AWTGraphicsDemo(){
      super("Java AWT Examples");
      prepareGUI();
   }

   public static void main(String[] args){
      AWTGraphicsDemo  awtGraphicsDemo = new AWTGraphicsDemo();  
      awtGraphicsDemo.setVisible(true);
   }

   private void prepareGUI(){
      setSize(400,400);
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      }); 
   }    

   @Override
   public void paint(Graphics g) {
      g.setColor(Color.GRAY);
      Font font = new Font("Serif", Font.PLAIN, 24);
      g.setFont(font);
      g.drawString("Welcome to TutorialsPoint", 50, 150);      
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AWTGraphicsDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo

Проверьте следующий вывод

AWT Graphics

AWT Graphics2D Class

Вступление

The Graphics2D class extends the Graphics class to provide more sophisticated control over geometry, coordinate transformations, color management, and text layout.

Объявление класса

Following is the declaration for java.awt.Graphics2D class:

public abstract class Graphics2D
   extends Graphics

Конструкторы классов

SN Конструктор и описание
1

Graphics2D()

Constructs a new Graphics2D object.

Graphics2D()

Constructs a new Graphics2D object.

Методы класса

SN Метод и описание
1

abstract void addRenderingHints(Map<?,?> hints)

Sets the values of an arbitrary number of preferences for the rendering algorithms.

2

abstract void clip(Shape s)

Intersects the current Clip with the interior of the specified Shape and sets the Clip to the resulting intersection.

3

abstract void draw(Shape s)

Strokes the outline of a Shape using the settings of the current Graphics2D context.

4

void draw3DRect(int x, int y, int width, int height, boolean raised)

Draws a 3-D highlighted outline of the specified rectangle.

5

abstract void drawGlyphVector(GlyphVector g, float x, float y)

Renders the text of the specified GlyphVector using the Graphics2D context’s rendering attributes.

6

abstract void drawImage(BufferedImage img, BufferedImageOp op, int x, int y)

Renders a BufferedImage that is filtered with a BufferedImageOp.

7

abstract boolean drawImage(Image img, AffineTransform xform, ImageObserver obs)

Renders an image, applying a transform from image space into user space before drawing.

8

abstract void drawRenderableImage(RenderableImage img, AffineTransform xform)

Renders a RenderableImage, applying a transform from image space into user space before drawing.

9

abstract void drawRenderedImage(RenderedImage img, AffineTransform xform)

Renders a RenderedImage, applying a transform from image space into user space before drawing.

10

abstract void drawString(AttributedCharacterIterator iterator, float x, float y)

Renders the text of the specified iterator applying its attributes in accordance with the specification of the TextAttribute class.

11

abstract void drawString(AttributedCharacterIterator iterator, int x, int y)

Renders the text of the specified iterator applying its attributes in accordance with the specification of the TextAttribute class.

12

abstract void drawString(String str, float x, float y)

Renders the text specified by the specified String, using the current text attribute state in the Graphics2D context

13

abstract void drawString(String str, int x, int y)

Renders the text of the specified String, using the current text attribute state in the Graphics2D context.

14

abstract void fill(Shape s)

Fills the interior of a Shape using the settings of the Graphics2D context.

15

void fill3DRect(int x, int y, int width, int height, boolean raised)

Paints a 3-D highlighted rectangle filled with the current color.

16

abstract Color getBackground()

Returns the background color used for clearing a region.

17

abstract Composite getComposite()

Returns the current Composite in the Graphics2D context.

18

abstract GraphicsConfiguration getDeviceConfiguration()

Returns the device configuration associated with this Graphics2D.

19

abstract FontRenderContext getFontRenderContext()

Get the rendering context of the Font within this Graphics2D context.

20

abstract Paint getPaint()

Returns the current Paint of the Graphics2D context.

21

abstract Object getRenderingHint(RenderingHints.Key hintKey)

Returns the value of a single preference for the rendering algorithms.

22

abstract RenderingHints getRenderingHints()

Gets the preferences for the rendering algorithms.

23

abstract Stroke getStroke()

Returns the current Stroke in the Graphics2D context.

24

abstract AffineTransform getTransform()

Returns a copy of the current Transform in the Graphics2D context.

25

abstract boolean hit(Rectangle rect, Shape s, boolean onStroke)

Checks whether or not the specified Shape intersects the specified Rectangle, which is in device space.

26

abstract void rotate(double theta)

Concatenates the current Graphics2D Transform with a rotation transform.

27

abstract void rotate(double theta, double x, double y)

Concatenates the current Graphics2D Transform with a translated rotation transform.

28

abstract void scale(double sx, double sy)

Concatenates the current Graphics2D Transform with a scaling transformation Subsequent rendering is resized according to the specified scaling factors relative to the previous scaling.

29

abstract void setBackground(Color color)

Sets the background color for the Graphics2D context.

30

abstract void setComposite(Composite comp)

Sets the Composite for the Graphics2D context.

31

abstract void setPaint(Paint paint)

Sets the Paint attribute for the Graphics2D context.

32

abstract void setRenderingHint(RenderingHints.Key hintKey, Object hintValue)

Sets the value of a single preference for the rendering algorithms.

33

abstract void setRenderingHints(Map<?,?> hints)

Replaces the values of all preferences for the rendering algorithms with the specified hints.

34

abstract void setStroke(Stroke s)

Sets the Stroke for the Graphics2D context.

35

abstract void setTransform(AffineTransform Tx)

Overwrites the Transform in the Graphics2D context.

36

abstract void shear(double shx, double shy)

Concatenates the current Graphics2D Transform with a shearing transform.

37

abstract void transform(AffineTransform Tx)

Composes an AffineTransform object with the Transform in this Graphics2D according to the rulelast-specified-first-applied.

38

abstract void translate(double tx, double ty)

Concatenates the current Graphics2D Transform with a translation transform.

39

abstract void translate(int x, int y)

Translates the origin of the Graphics2D context to the point (x, y) in the current coordinate system.

abstract void addRenderingHints(Map<?,?> hints)

Sets the values of an arbitrary number of preferences for the rendering algorithms.

abstract void clip(Shape s)

Intersects the current Clip with the interior of the specified Shape and sets the Clip to the resulting intersection.

abstract void draw(Shape s)

Strokes the outline of a Shape using the settings of the current Graphics2D context.

void draw3DRect(int x, int y, int width, int height, boolean raised)

Draws a 3-D highlighted outline of the specified rectangle.

abstract void drawGlyphVector(GlyphVector g, float x, float y)

Renders the text of the specified GlyphVector using the Graphics2D context’s rendering attributes.

abstract void drawImage(BufferedImage img, BufferedImageOp op, int x, int y)

Renders a BufferedImage that is filtered with a BufferedImageOp.

abstract boolean drawImage(Image img, AffineTransform xform, ImageObserver obs)

Renders an image, applying a transform from image space into user space before drawing.

abstract void drawRenderableImage(RenderableImage img, AffineTransform xform)

Renders a RenderableImage, applying a transform from image space into user space before drawing.

abstract void drawRenderedImage(RenderedImage img, AffineTransform xform)

Renders a RenderedImage, applying a transform from image space into user space before drawing.

abstract void drawString(AttributedCharacterIterator iterator, float x, float y)

Renders the text of the specified iterator applying its attributes in accordance with the specification of the TextAttribute class.

abstract void drawString(AttributedCharacterIterator iterator, int x, int y)

Renders the text of the specified iterator applying its attributes in accordance with the specification of the TextAttribute class.

abstract void drawString(String str, float x, float y)

Renders the text specified by the specified String, using the current text attribute state in the Graphics2D context

abstract void drawString(String str, int x, int y)

Renders the text of the specified String, using the current text attribute state in the Graphics2D context.

abstract void fill(Shape s)

Fills the interior of a Shape using the settings of the Graphics2D context.

void fill3DRect(int x, int y, int width, int height, boolean raised)

Paints a 3-D highlighted rectangle filled with the current color.

abstract Color getBackground()

Returns the background color used for clearing a region.

abstract Composite getComposite()

Returns the current Composite in the Graphics2D context.

abstract GraphicsConfiguration getDeviceConfiguration()

Returns the device configuration associated with this Graphics2D.

abstract FontRenderContext getFontRenderContext()

Get the rendering context of the Font within this Graphics2D context.

abstract Paint getPaint()

Returns the current Paint of the Graphics2D context.

abstract Object getRenderingHint(RenderingHints.Key hintKey)

Returns the value of a single preference for the rendering algorithms.

abstract RenderingHints getRenderingHints()

Gets the preferences for the rendering algorithms.

abstract Stroke getStroke()

Returns the current Stroke in the Graphics2D context.

abstract AffineTransform getTransform()

Returns a copy of the current Transform in the Graphics2D context.

abstract boolean hit(Rectangle rect, Shape s, boolean onStroke)

Checks whether or not the specified Shape intersects the specified Rectangle, which is in device space.

abstract void rotate(double theta)

Concatenates the current Graphics2D Transform with a rotation transform.

abstract void rotate(double theta, double x, double y)

Concatenates the current Graphics2D Transform with a translated rotation transform.

abstract void scale(double sx, double sy)

Concatenates the current Graphics2D Transform with a scaling transformation Subsequent rendering is resized according to the specified scaling factors relative to the previous scaling.

abstract void setBackground(Color color)

Sets the background color for the Graphics2D context.

abstract void setComposite(Composite comp)

Sets the Composite for the Graphics2D context.

abstract void setPaint(Paint paint)

Sets the Paint attribute for the Graphics2D context.

abstract void setRenderingHint(RenderingHints.Key hintKey, Object hintValue)

Sets the value of a single preference for the rendering algorithms.

abstract void setRenderingHints(Map<?,?> hints)

Replaces the values of all preferences for the rendering algorithms with the specified hints.

abstract void setStroke(Stroke s)

Sets the Stroke for the Graphics2D context.

abstract void setTransform(AffineTransform Tx)

Overwrites the Transform in the Graphics2D context.

abstract void shear(double shx, double shy)

Concatenates the current Graphics2D Transform with a shearing transform.

abstract void transform(AffineTransform Tx)

Composes an AffineTransform object with the Transform in this Graphics2D according to the rulelast-specified-first-applied.

abstract void translate(double tx, double ty)

Concatenates the current Graphics2D Transform with a translation transform.

abstract void translate(int x, int y)

Translates the origin of the Graphics2D context to the point (x, y) in the current coordinate system.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.lang.Object

java.lang.Object

Graphics2D Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AWTGraphicsDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

public class AWTGraphicsDemo extends Frame {
       
   public AWTGraphicsDemo(){
      super("Java AWT Examples");
      prepareGUI();
   }

   public static void main(String[] args){
      AWTGraphicsDemo  awtGraphicsDemo = new AWTGraphicsDemo();  
      awtGraphicsDemo.setVisible(true);
   }

   private void prepareGUI(){
      setSize(400,400);
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      }); 
   }    

   @Override
   public void paint(Graphics g) {
      Graphics2D g2 = (Graphics2D)g;
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
         RenderingHints.VALUE_ANTIALIAS_ON);
      Font font = new Font("Serif", Font.PLAIN, 24);
      g2.setFont(font);
      g2.drawString("Welcome to TutorialsPoint", 50, 70); 
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AWTGraphicsDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo

Проверьте следующий вывод

AWT Graphics2D

AWT Arc2D Class

Вступление

The Arc2D class is the superclass for all objects that store a 2D arc defined by a framing rectangle, start angle, angular extent (length of the arc), and a closure type (OPEN, CHORD, or PIE).

Объявление класса

Following is the declaration for java.awt.Arc2D class:

public abstract class Arc2D
   extends RectangularShape

поле

Following are the fields for java.awt.geom.Arc2D class:

  • static int CHORD — The closure type for an arc closed by drawing a straight line segment from the start of the arc segment to the end of the arc segment.

  • static int OPEN — The closure type for an open arc with no path segments connecting the two ends of the arc segment.

  • static int PIE — The closure type for an arc closed by drawing straight line segments from the start of the arc segment to the center of the full ellipse and from that point to the end of the arc segment.

static int CHORD — The closure type for an arc closed by drawing a straight line segment from the start of the arc segment to the end of the arc segment.

static int OPEN — The closure type for an open arc with no path segments connecting the two ends of the arc segment.

static int PIE — The closure type for an arc closed by drawing straight line segments from the start of the arc segment to the center of the full ellipse and from that point to the end of the arc segment.

Конструкторы классов

SN Конструктор и описание
1

protected Arc2D(int type)

This is an abstract class that cannot be instantiated directly.

protected Arc2D(int type)

This is an abstract class that cannot be instantiated directly.

Методы класса

SN Метод и описание
1

boolean contains(double x, double y)

Determines whether or not the specified point is inside the boundary of the arc.

2

boolean contains(double x, double y, double w, double h)

Determines whether or not the interior of the arc entirely contains the specified rectangle.

3

boolean contains(Rectangle2D r)

Determines whether or not the interior of the arc entirely contains the specified rectangle.

4

boolean containsAngle(double angle)

Determines whether or not the specified angle is within the angular extents of the arc.

5

логическое равенство (Object obj)

Determines whether or not the specified Object is equal to this Arc2D.

6

abstract double getAngleExtent()

Returns the angular extent of the arc.

7

abstract double getAngleStart()

Returns the starting angle of the arc.

8

int getArcType()

Returns the arc closure type of the arc: OPEN, CHORD, or PIE.

9

Rectangle2D getBounds2D()

Returns the high-precision framing rectangle of the arc.

10

Point2D getEndPoint()

Returns the ending point of the arc.

11

PathIterator getPathIterator(AffineTransform at)

Returns an iteration object that defines the boundary of the arc.

12

Point2D getStartPoint()

Returns the starting point of the arc.

13

int hashCode ()

Returns the hashcode for this Arc2D.

14

boolean intersects(double x, double y, double w, double h)

Determines whether or not the interior of the arc intersects the interior of the specified rectangle.

15

protected abstract Rectangle2D makeBounds(double x, double y, double w, double h)

Constructs a Rectangle2D of the appropriate precision to hold the parameters calculated to be the framing rectangle of this arc.

16

abstract void setAngleExtent(double angExt)

Sets the angular extent of this arc to the specified double value.

17

void setAngles(double x1, double y1, double x2, double y2)

Sets the starting angle and angular extent of this arc using two sets of coordinates.

18

void setAngles(Point2D p1, Point2D p2)

Sets the starting angle and angular extent of this arc using two points.

19

abstract void setAngleStart(double angSt)

Sets the starting angle of this arc to the specified double value.

20

void setAngleStart(Point2D p)

Sets the starting angle of this arc to the angle that the specified point defines relative to the center of this arc.

21

void setArc(Arc2D a)

Sets this arc to be the same as the specified arc.

22

abstract void setArc(double x, double y, double w, double h, double angSt, double angExt, int closure)

Sets the location, size, angular extents, and closure type of this arc to the specified double values.

23

void setArc(Point2D loc, Dimension2D size, double angSt, double angExt, int closure)

Sets the location, size, angular extents, and closure type of this arc to the specified values.

24

void setArc(Rectangle2D rect, double angSt, double angExt, int closure)

Sets the location, size, angular extents, and closure type of this arc to the specified values.

25

void setArcByCenter(double x, double y, double radius, double angSt, double angExt, int closure)

Sets the position, bounds, angular extents, and closure type of this arc to the specified values.

26

void setArcByTangent(Point2D p1, Point2D p2, Point2D p3, double radius)

Sets the position, bounds, and angular extents of this arc to the specified value.

27

void setArcType(int type)

Sets the closure type of this arc to the specified value: OPEN, CHORD, or PIE.

28

void setFrame(double x, double y, double w, double h)

Sets the location and size of the framing rectangle of this Shape to the specified rectangular values.

boolean contains(double x, double y)

Determines whether or not the specified point is inside the boundary of the arc.

boolean contains(double x, double y, double w, double h)

Determines whether or not the interior of the arc entirely contains the specified rectangle.

boolean contains(Rectangle2D r)

Determines whether or not the interior of the arc entirely contains the specified rectangle.

boolean containsAngle(double angle)

Determines whether or not the specified angle is within the angular extents of the arc.

логическое равенство (Object obj)

Determines whether or not the specified Object is equal to this Arc2D.

abstract double getAngleExtent()

Returns the angular extent of the arc.

abstract double getAngleStart()

Returns the starting angle of the arc.

int getArcType()

Returns the arc closure type of the arc: OPEN, CHORD, or PIE.

Rectangle2D getBounds2D()

Returns the high-precision framing rectangle of the arc.

Point2D getEndPoint()

Returns the ending point of the arc.

PathIterator getPathIterator(AffineTransform at)

Returns an iteration object that defines the boundary of the arc.

Point2D getStartPoint()

Returns the starting point of the arc.

int hashCode ()

Returns the hashcode for this Arc2D.

boolean intersects(double x, double y, double w, double h)

Determines whether or not the interior of the arc intersects the interior of the specified rectangle.

protected abstract Rectangle2D makeBounds(double x, double y, double w, double h)

Constructs a Rectangle2D of the appropriate precision to hold the parameters calculated to be the framing rectangle of this arc.

abstract void setAngleExtent(double angExt)

Sets the angular extent of this arc to the specified double value.

void setAngles(double x1, double y1, double x2, double y2)

Sets the starting angle and angular extent of this arc using two sets of coordinates.

void setAngles(Point2D p1, Point2D p2)

Sets the starting angle and angular extent of this arc using two points.

abstract void setAngleStart(double angSt)

Sets the starting angle of this arc to the specified double value.

void setAngleStart(Point2D p)

Sets the starting angle of this arc to the angle that the specified point defines relative to the center of this arc.

void setArc(Arc2D a)

Sets this arc to be the same as the specified arc.

abstract void setArc(double x, double y, double w, double h, double angSt, double angExt, int closure)

Sets the location, size, angular extents, and closure type of this arc to the specified double values.

void setArc(Point2D loc, Dimension2D size, double angSt, double angExt, int closure)

Sets the location, size, angular extents, and closure type of this arc to the specified values.

void setArc(Rectangle2D rect, double angSt, double angExt, int closure)

Sets the location, size, angular extents, and closure type of this arc to the specified values.

void setArcByCenter(double x, double y, double radius, double angSt, double angExt, int closure)

Sets the position, bounds, angular extents, and closure type of this arc to the specified values.

void setArcByTangent(Point2D p1, Point2D p2, Point2D p3, double radius)

Sets the position, bounds, and angular extents of this arc to the specified value.

void setArcType(int type)

Sets the closure type of this arc to the specified value: OPEN, CHORD, or PIE.

void setFrame(double x, double y, double w, double h)

Sets the location and size of the framing rectangle of this Shape to the specified rectangular values.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.awt.geom.RectangularShape

  • java.lang.Object

java.awt.geom.RectangularShape

java.lang.Object

Arc2D Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AWTGraphicsDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

public class AWTGraphicsDemo extends Frame {
       
   public AWTGraphicsDemo(){
      super("Java AWT Examples");
      prepareGUI();
   }

   public static void main(String[] args){
      AWTGraphicsDemo  awtGraphicsDemo = new AWTGraphicsDemo();  
      awtGraphicsDemo.setVisible(true);
   }

   private void prepareGUI(){
      setSize(400,400);
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      }); 
   }    

   @Override
   public void paint(Graphics g) {
      Arc2D.Float arc = new Arc2D.Float(Arc2D.PIE);
      arc.setFrame(70, 200, 150, 150);
      arc.setAngleStart(0);
      arc.setAngleExtent(145);
      Graphics2D g2 = (Graphics2D) g; 
      g2.setColor(Color.gray);
      g2.draw(arc);
      g2.setColor(Color.red);
      g2.fill(arc);
      g2.setColor(Color.black);
      Font font = new Font("Serif", Font.PLAIN, 24);
      g2.setFont(font);
      g.drawString("Welcome to TutorialsPoint", 50, 70);
      g2.drawString("Arc2D.PIE", 100, 120); 
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtGraphicsDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtGraphicsDemo

Проверьте следующий вывод

AWT Arc2D

AWT CubicCurve2D Class

Вступление

The CubicCurve2D class states a cubic parametric curve segment in (x,y) coordinate space.

Объявление класса

Following is the declaration for java.awt.geom.CubicCurve2D class:

public abstract class CubicCurve2D
   extends Object
      implements Shape, Cloneable

Конструкторы классов

SN Конструктор и описание
1

protected CubicCurve2D()

This is an abstract class that cannot be instantiated directly.

protected CubicCurve2D()

This is an abstract class that cannot be instantiated directly.

Методы класса

SN Метод и описание
1

Object clone()

Creates a new object of the same class as this object.

2

boolean contains(double x, double y)

Tests if the specified coordinates are inside the boundary of the Shape.

3

boolean contains(double x, double y, double w, double h)

Tests if the interior of the Shape entirely contains the specified rectangular area.

4

boolean contains(Point2D p)

Tests if a specified Point2D is inside the boundary of the Shape.

5

boolean contains(Rectangle2D r)

Tests if the interior of the Shape entirely contains the specified Rectangle2D.

6

Rectangle getBounds()

Returns an integer Rectangle that completely encloses the Shape.

7

abstract Point2D getCtrlP1()

Returns the first control point.

8

abstract Point2D getCtrlP2()

Returns the second control point.

9

abstract double getCtrlX1()

Returns the X coordinate of the first control point in double precision.

10

abstract double getCtrlX2()

Returns the X coordinate of the second control point in double precision.

11

abstract double getCtrlY1()

Returns the Y coordinate of the first control point in double precision.

12

abstract double getCtrlY2()

Returns the Y coordinate of the second control point in double precision.

13

double getFlatness()

Returns the flatness of this curve.

14

static double getFlatness(double[] coords, int offset)

Returns the flatness of the cubic curve specified by the control points stored in the indicated array at the indicated index.

15

static double getFlatness(double x1, double y1, double ctrlx1, double ctrly1, double ctrlx2, double ctrly2, double x2, double y2)

Returns the flatness of the cubic curve specified by the indicated control points.

16

double getFlatnessSq()

Returns the square of the flatness of this curve.

17

static double getFlatnessSq(double[] coords, int offset)

Returns the square of the flatness of the cubic curve specified by the control points stored in the indicated array at the indicated index.

18

static double getFlatnessSq(double x1, double y1, double ctrlx1, double ctrly1, double ctrlx2, double ctrly2, double x2, double y2)

Returns the square of the flatness of the cubic curve specified by the indicated control points.

19

abstract Point2D getP1()

Returns the start point.

20

abstract Point2D getP2()

Returns the end point.

21

PathIterator getPathIterator(AffineTransform at)

Returns an iteration object that defines the boundary of the shape.

22

PathIterator getPathIterator(AffineTransform at, double flatness)

Return an iteration object that defines the boundary of the flattened shape.

23

abstract double getX1()

Returns the X coordinate of the start point in double precision.

24

abstract double getX2()

Returns the X coordinate of the end point in double precision.

25

abstract double getY1()

Returns the Y coordinate of the start point in double precision.

26

abstract double getY2()

Returns the Y coordinate of the end point in double precision.

27

boolean intersects(double x, double y, double w, double h)

Tests if the interior of the Shape intersects the interior of a specified rectangular area.

28

boolean intersects(Rectangle2D r)

Tests if the interior of the Shape intersects the interior of a specified Rectangle2D.

29

void setCurve(CubicCurve2D c)

Sets the location of the end points and control points of this curve to the same as those in the specified CubicCurve2D.

30

void setCurve(double[] coords, int offset)

Sets the location of the end points and control points of this curve to the double coordinates at the specified offset in the specified array.

31

abstract void setCurve(double x1, double y1, double ctrlx1, double ctrly1, double ctrlx2, double ctrly2, double x2, double y2)

Sets the location of the end points and control points of this curve to the specified double coordinates.

32

void setCurve(Point2D[] pts, int offset)

Sets the location of the end points and control points of this curve to the coordinates of the Point2D objects at the specified offset in the specified array.

33

void setCurve(Point2D p1, Point2D cp1, Point2D cp2, Point2D p2)

Sets the location of the end points and control points of this curve to the specified Point2D coordinates.

34

static int solveCubic(double[] eqn)

Solves the cubic whose coefficients are in the eqn array and places the non-complex roots back into the same array, returning the number of roots.

35

static int solveCubic(double[] eqn, double[] res)

Solve the cubic whose coefficients are in the eqn array and place the non-complex roots into the res array, returning the number of roots.

36

void subdivide(CubicCurve2D left, CubicCurve2D right)

Subdivides this cubic curve and stores the resulting two subdivided curves into the left and right curve parameters.

37

static void subdivide(CubicCurve2D src, CubicCurve2D left, CubicCurve2D right)

Subdivides the cubic curve specified by the src parameter and stores the resulting two subdivided curves into the left and right curve parameters.

38

static void subdivide(double[] src, int srcoff, double[] left, int leftoff, double[] right, int rightoff)

Subdivides the cubic curve specified by the coordinates stored in the src array at indices srcoff through (srcoff + 7) and stores the resulting two subdivided curves into the two result arrays at the corresponding indices.

Object clone()

Creates a new object of the same class as this object.

boolean contains(double x, double y)

Tests if the specified coordinates are inside the boundary of the Shape.

boolean contains(double x, double y, double w, double h)

Tests if the interior of the Shape entirely contains the specified rectangular area.

boolean contains(Point2D p)

Tests if a specified Point2D is inside the boundary of the Shape.

boolean contains(Rectangle2D r)

Tests if the interior of the Shape entirely contains the specified Rectangle2D.

Rectangle getBounds()

Returns an integer Rectangle that completely encloses the Shape.

abstract Point2D getCtrlP1()

Returns the first control point.

abstract Point2D getCtrlP2()

Returns the second control point.

abstract double getCtrlX1()

Returns the X coordinate of the first control point in double precision.

abstract double getCtrlX2()

Returns the X coordinate of the second control point in double precision.

abstract double getCtrlY1()

Returns the Y coordinate of the first control point in double precision.

abstract double getCtrlY2()

Returns the Y coordinate of the second control point in double precision.

double getFlatness()

Returns the flatness of this curve.

static double getFlatness(double[] coords, int offset)

Returns the flatness of the cubic curve specified by the control points stored in the indicated array at the indicated index.

static double getFlatness(double x1, double y1, double ctrlx1, double ctrly1, double ctrlx2, double ctrly2, double x2, double y2)

Returns the flatness of the cubic curve specified by the indicated control points.

double getFlatnessSq()

Returns the square of the flatness of this curve.

static double getFlatnessSq(double[] coords, int offset)

Returns the square of the flatness of the cubic curve specified by the control points stored in the indicated array at the indicated index.

static double getFlatnessSq(double x1, double y1, double ctrlx1, double ctrly1, double ctrlx2, double ctrly2, double x2, double y2)

Returns the square of the flatness of the cubic curve specified by the indicated control points.

abstract Point2D getP1()

Returns the start point.

abstract Point2D getP2()

Returns the end point.

PathIterator getPathIterator(AffineTransform at)

Returns an iteration object that defines the boundary of the shape.

PathIterator getPathIterator(AffineTransform at, double flatness)

Return an iteration object that defines the boundary of the flattened shape.

abstract double getX1()

Returns the X coordinate of the start point in double precision.

abstract double getX2()

Returns the X coordinate of the end point in double precision.

abstract double getY1()

Returns the Y coordinate of the start point in double precision.

abstract double getY2()

Returns the Y coordinate of the end point in double precision.

boolean intersects(double x, double y, double w, double h)

Tests if the interior of the Shape intersects the interior of a specified rectangular area.

boolean intersects(Rectangle2D r)

Tests if the interior of the Shape intersects the interior of a specified Rectangle2D.

void setCurve(CubicCurve2D c)

Sets the location of the end points and control points of this curve to the same as those in the specified CubicCurve2D.

void setCurve(double[] coords, int offset)

Sets the location of the end points and control points of this curve to the double coordinates at the specified offset in the specified array.

abstract void setCurve(double x1, double y1, double ctrlx1, double ctrly1, double ctrlx2, double ctrly2, double x2, double y2)

Sets the location of the end points and control points of this curve to the specified double coordinates.

void setCurve(Point2D[] pts, int offset)

Sets the location of the end points and control points of this curve to the coordinates of the Point2D objects at the specified offset in the specified array.

void setCurve(Point2D p1, Point2D cp1, Point2D cp2, Point2D p2)

Sets the location of the end points and control points of this curve to the specified Point2D coordinates.

static int solveCubic(double[] eqn)

Solves the cubic whose coefficients are in the eqn array and places the non-complex roots back into the same array, returning the number of roots.

static int solveCubic(double[] eqn, double[] res)

Solve the cubic whose coefficients are in the eqn array and place the non-complex roots into the res array, returning the number of roots.

void subdivide(CubicCurve2D left, CubicCurve2D right)

Subdivides this cubic curve and stores the resulting two subdivided curves into the left and right curve parameters.

static void subdivide(CubicCurve2D src, CubicCurve2D left, CubicCurve2D right)

Subdivides the cubic curve specified by the src parameter and stores the resulting two subdivided curves into the left and right curve parameters.

static void subdivide(double[] src, int srcoff, double[] left, int leftoff, double[] right, int rightoff)

Subdivides the cubic curve specified by the coordinates stored in the src array at indices srcoff through (srcoff + 7) and stores the resulting two subdivided curves into the two result arrays at the corresponding indices.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.lang.Object

java.lang.Object

CubicCurve2D Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AWTGraphicsDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

public class AWTGraphicsDemo extends Frame {
       
   public AWTGraphicsDemo(){
      super("Java AWT Examples");
      prepareGUI();
   }

   public static void main(String[] args){
      AWTGraphicsDemo  awtGraphicsDemo = new AWTGraphicsDemo();  
      awtGraphicsDemo.setVisible(true);
   }

   private void prepareGUI(){
      setSize(400,400);
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      }); 
   }    

   @Override
   public void paint(Graphics g) {
      CubicCurve2D shape = new CubicCurve2D.Float();
      shape.setCurve(250F,250F,20F,90F,140F,100F,350F,330F);       
      Graphics2D g2 = (Graphics2D) g; 
      g2.draw (shape);
      Font font = new Font("Serif", Font.PLAIN, 24);
      g2.setFont(font);
      g.drawString("Welcome to TutorialsPoint", 50, 70);
      g2.drawString("CubicCurve2D.Curve", 100, 120);
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AWTGraphicsDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo

Проверьте следующий вывод

AWT CubicCurve2D

AWT Ellipse2D Class

Вступление

The Ellipse2D class states an ellipse that is defined by a framing rectangle.

Объявление класса

Following is the declaration for java.awt.geom.Ellipse2D class:

public abstract class Ellipse2D
   extends RectangularShape

Конструкторы классов

SN Конструктор и описание
1

protected Ellipse2D()

This is an abstract class that cannot be instantiated directly.

protected Ellipse2D()

This is an abstract class that cannot be instantiated directly.

Методы класса

SN Метод и описание
1

boolean contains(double x, double y)

Tests if the specified coordinates are inside the boundary of the Shape.

2

boolean contains(double x, double y, double w, double h)

Tests if the interior of the Shape entirely contains the specified rectangular area.

3

логическое равенство (Object obj)

Determines whether or not the specified Object is equal to this Ellipse2D.

4

PathIterator getPathIterator(AffineTransform at)

Returns an iteration object that defines the boundary of this Ellipse2D.

5

int hashCode ()

Returns the hashcode for this Ellipse2D.

6

boolean intersects(double x, double y, double w, double h)

Tests if the interior of the Shape intersects the interior of a specified rectangular area.

boolean contains(double x, double y)

Tests if the specified coordinates are inside the boundary of the Shape.

boolean contains(double x, double y, double w, double h)

Tests if the interior of the Shape entirely contains the specified rectangular area.

логическое равенство (Object obj)

Determines whether or not the specified Object is equal to this Ellipse2D.

PathIterator getPathIterator(AffineTransform at)

Returns an iteration object that defines the boundary of this Ellipse2D.

int hashCode ()

Returns the hashcode for this Ellipse2D.

boolean intersects(double x, double y, double w, double h)

Tests if the interior of the Shape intersects the interior of a specified rectangular area.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.lang.Object

java.lang.Object

Ellipse2D Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AWTGraphicsDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

public class AWTGraphicsDemo extends Frame {
       
   public AWTGraphicsDemo(){
      super("Java AWT Examples");
      prepareGUI();
   }

   public static void main(String[] args){
      AWTGraphicsDemo  awtGraphicsDemo = new AWTGraphicsDemo();  
      awtGraphicsDemo.setVisible(true);
   }

   private void prepareGUI(){
      setSize(400,400);
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      }); 
   }    

   @Override
   public void paint(Graphics g) {
      Ellipse2D shape = new Ellipse2D.Float();
      shape.setFrame(100, 150, 200,100);
      Graphics2D g2 = (Graphics2D) g; 
      g2.draw (shape);
      Font font = new Font("Serif", Font.PLAIN, 24);
      g2.setFont(font);
      g.drawString("Welcome to TutorialsPoint", 50, 70);
      g2.drawString("Ellipse2D.Oval", 100, 120); 
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AWTGraphicsDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo

Проверьте следующий вывод

AWT Ellipse2D

AWT Rectangle2D Class

Вступление

The Rectangle2D class states a rectangle defined by a location (x,y) and dimension (wxh).

Объявление класса

Following is the declaration for java.awt.geom.Rectangle2D class:

public abstract class Rectangle2D
   extends RectangularShape

поле

Following are the fields for java.awt.geom.Arc2D class:

  • static int OUT_BOTTOM — The bitmask that indicates that a point lies below this Rectangle2D.

  • static int OUT_LEFT — The bitmask that indicates that a point lies to the left of this Rectangle2D.

  • static int OUT_RIGHT — The bitmask that indicates that a point lies to the right of this Rectangle2D.

  • static int OUT_TOP — The bitmask that indicates that a point lies above this Rectangle2D.

static int OUT_BOTTOM — The bitmask that indicates that a point lies below this Rectangle2D.

static int OUT_LEFT — The bitmask that indicates that a point lies to the left of this Rectangle2D.

static int OUT_RIGHT — The bitmask that indicates that a point lies to the right of this Rectangle2D.

static int OUT_TOP — The bitmask that indicates that a point lies above this Rectangle2D.

Конструкторы классов

SN Конструктор и описание
1

protected Rectangle2D()

This is an abstract class that cannot be instantiated directly.

protected Rectangle2D()

This is an abstract class that cannot be instantiated directly.

Методы класса

SN Метод и описание
1

void add(double newx, double newy)

Adds a point, specified by the double precision arguments newx and newy, to this Rectangle2D.

2

void add(Point2D pt)

Adds the Point2D object pt to this Rectangle2D.

3

void add(Rectangle2D r)

Adds a Rectangle2D object to this Rectangle2D.

4

boolean contains(double x, double y)

Tests if the specified coordinates are inside the boundary of the Shape.

5

boolean contains(double x, double y, double w, double h)

Tests if the interior of the Shape entirely contains the specified rectangular area.

6

abstract Rectangle2D createIntersection(Rectangle2D r)

Returns a new Rectangle2D object representing the intersection of this Rectangle2D with the specified Rectangle2D.

7

abstract Rectangle2D createUnion(Rectangle2D r)

Returns a new Rectangle2D object representing the union of this Rectangle2D with the specified Rectangle2D.

8

логическое равенство (Object obj)

Determines whether or not the specified Object is equal to this Rectangle2D.

9

Rectangle2D getBounds2D()

Returns a high precision and more accurate bounding box of the Shape than the getBounds method.

10

PathIterator getPathIterator(AffineTransform at)

Returns an iteration object that defines the boundary of this Rectangle2D.

11

PathIterator getPathIterator(AffineTransform at, double flatness)

Returns an iteration object that defines the boundary of the flattened Rectangle2D.

12

int hashCode ()

Returns the hashcode for this Rectangle2D.

13

static void intersect(Rectangle2D src1, Rectangle2D src2, Rectangle2D dest)

Intersects the pair of specified source Rectangle2D objects and puts the result into the specified destination Rectangle2D object.

14

boolean intersects(double x, double y, double w, double h)

Tests if the interior of the Shape intersects the interior of a specified rectangular area.

15

boolean intersectsLine(double x1, double y1, double x2, double y2)

Tests if the specified line segment intersects the interior of this Rectangle2D.

16

boolean intersectsLine(Line2D l)

Tests if the specified line segment intersects the interior of this Rectangle2D.

17

abstract int outcode(double x, double y)

Determines where the specified coordinates lie with respect to this Rectangle2D.

18

int outcode(Point2D p)

Determines where the specified Point2D lies with respect to this Rectangle2D.

19

void setFrame(double x, double y, double w, double h)

Sets the location and size of the outer bounds of this Rectangle2D to the specified rectangular values.

20

abstract void setRect(double x, double y, double w, double h)

Sets the location and size of this Rectangle2D to the specified double values.

21

void setRect(Rectangle2D r)

Sets this Rectangle2D to be the same as the specified Rectangle2D.

22

static void union(Rectangle2D src1, Rectangle2D src2, Rectangle2D dest)

Unions the pair of source Rectangle2D objects and puts the result into the specified destination Rectangle2D object.

void add(double newx, double newy)

Adds a point, specified by the double precision arguments newx and newy, to this Rectangle2D.

void add(Point2D pt)

Adds the Point2D object pt to this Rectangle2D.

void add(Rectangle2D r)

Adds a Rectangle2D object to this Rectangle2D.

boolean contains(double x, double y)

Tests if the specified coordinates are inside the boundary of the Shape.

boolean contains(double x, double y, double w, double h)

Tests if the interior of the Shape entirely contains the specified rectangular area.

abstract Rectangle2D createIntersection(Rectangle2D r)

Returns a new Rectangle2D object representing the intersection of this Rectangle2D with the specified Rectangle2D.

abstract Rectangle2D createUnion(Rectangle2D r)

Returns a new Rectangle2D object representing the union of this Rectangle2D with the specified Rectangle2D.

логическое равенство (Object obj)

Determines whether or not the specified Object is equal to this Rectangle2D.

Rectangle2D getBounds2D()

Returns a high precision and more accurate bounding box of the Shape than the getBounds method.

PathIterator getPathIterator(AffineTransform at)

Returns an iteration object that defines the boundary of this Rectangle2D.

PathIterator getPathIterator(AffineTransform at, double flatness)

Returns an iteration object that defines the boundary of the flattened Rectangle2D.

int hashCode ()

Returns the hashcode for this Rectangle2D.

static void intersect(Rectangle2D src1, Rectangle2D src2, Rectangle2D dest)

Intersects the pair of specified source Rectangle2D objects and puts the result into the specified destination Rectangle2D object.

boolean intersects(double x, double y, double w, double h)

Tests if the interior of the Shape intersects the interior of a specified rectangular area.

boolean intersectsLine(double x1, double y1, double x2, double y2)

Tests if the specified line segment intersects the interior of this Rectangle2D.

boolean intersectsLine(Line2D l)

Tests if the specified line segment intersects the interior of this Rectangle2D.

abstract int outcode(double x, double y)

Determines where the specified coordinates lie with respect to this Rectangle2D.

int outcode(Point2D p)

Determines where the specified Point2D lies with respect to this Rectangle2D.

void setFrame(double x, double y, double w, double h)

Sets the location and size of the outer bounds of this Rectangle2D to the specified rectangular values.

abstract void setRect(double x, double y, double w, double h)

Sets the location and size of this Rectangle2D to the specified double values.

void setRect(Rectangle2D r)

Sets this Rectangle2D to be the same as the specified Rectangle2D.

static void union(Rectangle2D src1, Rectangle2D src2, Rectangle2D dest)

Unions the pair of source Rectangle2D objects and puts the result into the specified destination Rectangle2D object.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.awt.geom.RectangularShape

  • java.lang.Object

java.awt.geom.RectangularShape

java.lang.Object

Ellipse2D Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AWTGraphicsDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

public class AWTGraphicsDemo extends Frame {
       
   public AWTGraphicsDemo(){
      super("Java AWT Examples");
      prepareGUI();
   }

   public static void main(String[] args){
      AWTGraphicsDemo  awtGraphicsDemo = new AWTGraphicsDemo();  
      awtGraphicsDemo.setVisible(true);
   }

   private void prepareGUI(){
      setSize(400,400);
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      }); 
   }    

   @Override
   public void paint(Graphics g) {
      Rectangle2D shape = new Rectangle2D.Float();
      shape.setFrame(100, 150, 200,100);
      Graphics2D g2 = (Graphics2D) g; 
      g2.draw (shape);
      Font font = new Font("Serif", Font.PLAIN, 24);
      g2.setFont(font);
      g.drawString("Welcome to TutorialsPoint", 50, 70);
      g2.drawString("Rectangle2D.Rectangle", 100, 120);
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AWTGraphicsDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo

Проверьте следующий вывод

AWT Rectangle2D

AWT QuadCurve2D Class

Вступление

The QuadCurve2D class states a quadratic parametric curve segment in (x,y) coordinate space.

Объявление класса

Following is the declaration for java.awt.geom.QuadCurve2D class:

public abstract class QuadCurve2D
   extends Object
      implements Shape, Cloneable

Конструкторы классов

SN Конструктор и описание
1

protected QuadCurve2D() ()

This is an abstract class that cannot be instantiated directly.

protected QuadCurve2D() ()

This is an abstract class that cannot be instantiated directly.

Методы класса

SN Метод и описание
1

Object clone()

Creates a new object of the same class and with the same contents as this object.

2

boolean contains(double x, double y)

Tests if the specified coordinates are inside the boundary of the Shape.

3

boolean contains(double x, double y, double w, double h)

Tests if the interior of the Shape entirely contains the specified rectangular area.

4

boolean contains(Point2D p)

Tests if a specified Point2D is inside the boundary of the Shape.

5

boolean contains(Rectangle2D r)

Tests if the interior of the Shape entirely contains the specified Rectangle2D.

6

Rectangle getBounds()

Returns an integer Rectangle that completely encloses the Shape.

7

abstract Point2D getCtrlPt()

Returns the control point.

8

abstract double getCtrlX()

Returns the X coordinate of the control point in double precision.

9

abstract double getCtrlY()

Returns the Y coordinate of the control point in double precision.

10

doublegetFlatness()

Returns the flatness, or maximum distance of a control point from the line connecting the end points, of this QuadCurve2D.

11

static double getFlatness(double[] coords, int offset)

Returns the flatness, or maximum distance of a control point from the line connecting the end points, of the quadratic curve specified by the control points stored in the indicated array at the indicated index.

12

static double getFlatness(double x1, double y1, double ctrlx, double ctrly, double x2, double y2)

Returns the flatness, or maximum distance of a control point from the line connecting the end points, of the quadratic curve specified by the indicated control points.

13

double getFlatnessSq()

Returns the square of the flatness, or maximum distance of a control point from the line connecting the end points, of this QuadCurve2D.

14

static double getFlatnessSq(double[] coords, int offset)

Returns the square of the flatness, or maximum distance of a control point from the line connecting the end points, of the quadratic curve specified by the control points stored in the indicated array at the indicated index.

15

static double getFlatnessSq(double x1, double y1, double ctrlx, double ctrly, double x2, double y2)

Returns the square of the flatness, or maximum distance of a control point from the line connecting the end points, of the quadratic curve specified by the indicated control points.

16

abstract Point2D getP1()

Returns the start point.

17

abstract Point2D getP2()

Returns the end point.

18

PathIterator getPathIterator(AffineTransform at)

Returns an iteration object that defines the boundary of the shape of this QuadCurve2D.

19

PathIterator getPathIterator(AffineTransform at, double flatness)

Returns an iteration object that defines the boundary of the flattened shape of this QuadCurve2D.

20

abstract double getX1()

Returns the X coordinate of the start point in double in precision.

21

abstract double getX2()

Returns the X coordinate of the end point in double precision.

22

abstract double getY1()

Returns the Y coordinate of the start point in double precision.

23

abstract double getY2()

Returns the Y coordinate of the end point in double precision.

24

boolean intersects(double x, double y, double w, double h)

Tests if the interior of the Shape intersects the interior of a specified rectangular area.

25

boolean intersects(Rectangle2D r)

Tests if the interior of the Shape intersects the interior of a specified Rectangle2D.

26

void setCurve(double[] coords, int offset)

Sets the location of the end points and control points of this QuadCurve2D to the double coordinates at the specified offset in the specified array.

27

abstract void setCurve(double x1, double y1, double ctrlx, double ctrly, double x2, double y2)

Sets the location of the end points and control point of this curve to the specified double coordinates.

28

void setCurve(Point2D[] pts, int offset)

Sets the location of the end points and control points of this QuadCurve2D to the coordinates of the Point2D objects at the specified offset in the specified array.

29

void setCurve(Point2D p1, Point2D cp, Point2D p2)

Sets the location of the end points and control point of this QuadCurve2D to the specified Point2D coordinates.

30

void setCurve(QuadCurve2D c)

Sets the location of the end points and control point of this QuadCurve2D to the same as those in the specified QuadCurve2D.

31

static int solveQuadratic(double[] eqn)

Solves the quadratic whose coefficients are in the eqn array and places the non-complex roots back into the same array, returning the number of roots.

32

static int solveQuadratic(double[] eqn, double[] res)

Solves the quadratic whose coefficients are in the eqn array and places the non-complex roots into the res array, returning the number of roots.

33

static void subdivide(double[] src, int srcoff, double[] left, int leftoff, double[] right, int rightoff)

Subdivides the quadratic curve specified by the coordinates stored in the src array at indices srcoff through srcoff + 5 and stores the resulting two subdivided curves into the two result arrays at the corresponding indices.

34

void subdivide(QuadCurve2D left, QuadCurve2D right)

Subdivides this QuadCurve2D and stores the resulting two subdivided curves into the left and right curve parameters.

35

static void subdivide(QuadCurve2D src, QuadCurve2D left, QuadCurve2D right)

Subdivides the quadratic curve specified by the src parameter and stores the resulting two subdivided curves into the left and right curve parameters.

Object clone()

Creates a new object of the same class and with the same contents as this object.

boolean contains(double x, double y)

Tests if the specified coordinates are inside the boundary of the Shape.

boolean contains(double x, double y, double w, double h)

Tests if the interior of the Shape entirely contains the specified rectangular area.

boolean contains(Point2D p)

Tests if a specified Point2D is inside the boundary of the Shape.

boolean contains(Rectangle2D r)

Tests if the interior of the Shape entirely contains the specified Rectangle2D.

Rectangle getBounds()

Returns an integer Rectangle that completely encloses the Shape.

abstract Point2D getCtrlPt()

Returns the control point.

abstract double getCtrlX()

Returns the X coordinate of the control point in double precision.

abstract double getCtrlY()

Returns the Y coordinate of the control point in double precision.

doublegetFlatness()

Returns the flatness, or maximum distance of a control point from the line connecting the end points, of this QuadCurve2D.

static double getFlatness(double[] coords, int offset)

Returns the flatness, or maximum distance of a control point from the line connecting the end points, of the quadratic curve specified by the control points stored in the indicated array at the indicated index.

static double getFlatness(double x1, double y1, double ctrlx, double ctrly, double x2, double y2)

Returns the flatness, or maximum distance of a control point from the line connecting the end points, of the quadratic curve specified by the indicated control points.

double getFlatnessSq()

Returns the square of the flatness, or maximum distance of a control point from the line connecting the end points, of this QuadCurve2D.

static double getFlatnessSq(double[] coords, int offset)

Returns the square of the flatness, or maximum distance of a control point from the line connecting the end points, of the quadratic curve specified by the control points stored in the indicated array at the indicated index.

static double getFlatnessSq(double x1, double y1, double ctrlx, double ctrly, double x2, double y2)

Returns the square of the flatness, or maximum distance of a control point from the line connecting the end points, of the quadratic curve specified by the indicated control points.

abstract Point2D getP1()

Returns the start point.

abstract Point2D getP2()

Returns the end point.

PathIterator getPathIterator(AffineTransform at)

Returns an iteration object that defines the boundary of the shape of this QuadCurve2D.

PathIterator getPathIterator(AffineTransform at, double flatness)

Returns an iteration object that defines the boundary of the flattened shape of this QuadCurve2D.

abstract double getX1()

Returns the X coordinate of the start point in double in precision.

abstract double getX2()

Returns the X coordinate of the end point in double precision.

abstract double getY1()

Returns the Y coordinate of the start point in double precision.

abstract double getY2()

Returns the Y coordinate of the end point in double precision.

boolean intersects(double x, double y, double w, double h)

Tests if the interior of the Shape intersects the interior of a specified rectangular area.

boolean intersects(Rectangle2D r)

Tests if the interior of the Shape intersects the interior of a specified Rectangle2D.

void setCurve(double[] coords, int offset)

Sets the location of the end points and control points of this QuadCurve2D to the double coordinates at the specified offset in the specified array.

abstract void setCurve(double x1, double y1, double ctrlx, double ctrly, double x2, double y2)

Sets the location of the end points and control point of this curve to the specified double coordinates.

void setCurve(Point2D[] pts, int offset)

Sets the location of the end points and control points of this QuadCurve2D to the coordinates of the Point2D objects at the specified offset in the specified array.

void setCurve(Point2D p1, Point2D cp, Point2D p2)

Sets the location of the end points and control point of this QuadCurve2D to the specified Point2D coordinates.

void setCurve(QuadCurve2D c)

Sets the location of the end points and control point of this QuadCurve2D to the same as those in the specified QuadCurve2D.

static int solveQuadratic(double[] eqn)

Solves the quadratic whose coefficients are in the eqn array and places the non-complex roots back into the same array, returning the number of roots.

static int solveQuadratic(double[] eqn, double[] res)

Solves the quadratic whose coefficients are in the eqn array and places the non-complex roots into the res array, returning the number of roots.

static void subdivide(double[] src, int srcoff, double[] left, int leftoff, double[] right, int rightoff)

Subdivides the quadratic curve specified by the coordinates stored in the src array at indices srcoff through srcoff + 5 and stores the resulting two subdivided curves into the two result arrays at the corresponding indices.

void subdivide(QuadCurve2D left, QuadCurve2D right)

Subdivides this QuadCurve2D and stores the resulting two subdivided curves into the left and right curve parameters.

static void subdivide(QuadCurve2D src, QuadCurve2D left, QuadCurve2D right)

Subdivides the quadratic curve specified by the src parameter and stores the resulting two subdivided curves into the left and right curve parameters.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.lang.Object

java.lang.Object

QuadCurve2D Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AWTGraphicsDemo

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

public class AWTGraphicsDemo extends Frame {
       
   public AWTGraphicsDemo(){
      super("Java AWT Examples");
      prepareGUI();
   }

   public static void main(String[] args){
      AWTGraphicsDemo  awtGraphicsDemo = new AWTGraphicsDemo();  
      awtGraphicsDemo.setVisible(true);
   }

   private void prepareGUI(){
      setSize(400,400);
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      }); 
   }    

   @Override
   public void paint(Graphics g) {
      QuadCurve2D shape = new QuadCurve2D.Double();
      shape.setCurve(250D,250D,100D,100D,200D,150D);  
      Graphics2D g2 = (Graphics2D) g; 
      g2.draw (shape);
      Font font = new Font("Serif", Font.PLAIN, 24);
      g2.setFont(font);
      g.drawString("Welcome to TutorialsPoint", 50, 70);
      g2.drawString("QuadCurve2D.Curve", 100, 120);  
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AWTGraphicsDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo

Проверьте следующий вывод

AWT QuadCurve2D

AWT Line2D Class

Вступление

The Line2D class states a line segment in (x,y) coordinate space.

Объявление класса

Following is the declaration for java.awt.geom.Line2D class:

public abstract class Line2D
   extends Object
      implements Shape, Cloneable

Конструкторы классов

SN Конструктор и описание
1

protected Line2D() ()

This is an abstract class that cannot be instantiated directly.

protected Line2D() ()

This is an abstract class that cannot be instantiated directly.

Методы класса

SN Метод и описание
1

Object clone()

Creates a new object of the same class as this object.

2

boolean contains(double x, double y)

Tests if a specified coordinate is inside the boundary of this Line2D.

3

boolean contains(double x, double y, double w, double h)

Tests if the interior of this Line2D entirely contains the specified set of rectangular coordinates.

4

boolean contains(Point2D p)

Tests if a given Point2D is inside the boundary of this Line2D.

5

boolean contains(Rectangle2D r)

Tests if the interior of this Line2D entirely contains the specified Rectangle2D.

6

Rectangle getBounds()

Returns an integer Rectangle that completely encloses the Shape.

7

abstract Point2D getP1()

Returns the start Point2D of this Line2D.

8

abstract Point2D getP2()

Returns the end Point2D of this Line2D.

9

PathIterator getPathIterator(AffineTransform at)

Returns an iteration object that defines the boundary of this Line2D.

10

PathIterator getPathIterator(AffineTransform at, double flatness)

Returns an iteration object that defines the boundary of this flattened Line2D.

11

abstract double getX1()

Returns the X coordinate of the start point in double precision.

12

abstract double getX2()

Returns the X coordinate of the end point in double precision.

13

abstract double getY1()

Returns the Y coordinate of the start point in double precision.

14

abstract double getY2()

Returns the Y coordinate of the end point in double precision.

15

boolean intersects(double x, double y, double w, double h)

Tests if the interior of the Shape intersects the interior of a specified rectangular area.

16

boolean intersects(Rectangle2D r)

Tests if the interior of the Shape intersects the interior of a specified Rectangle2D.

17

boolean intersectsLine(double x1, double y1, double x2, double y2)

Tests if the line segment from (x1,y1) to (x2,y2) intersects this line segment.

18

boolean intersectsLine(Line2D l)

Tests if the specified line segment intersects this line segment.

19

static boolean linesIntersect(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4)

Tests if the line segment from (x1,y1) to (x2,y2) intersects the line segment from (x3,y3) to (x4,y4).

20

double ptLineDist(double px, double py)

Returns the distance from a point to this line.

21

static double ptLineDist(double x1, double y1, double x2, double y2, double px, double py)

Returns the distance from a point to a line.

22

double ptLineDist(Point2D pt)

Returns the distance from a Point2D to this line.

23

double ptLineDistSq(double px, double py)

Returns the square of the distance from a point to this line.

24

static double ptLineDistSq(double x1, double y1, double x2, double y2, double px, double py)

Returns the square of the distance from a point to a line.

25

double ptLineDistSq(Point2D pt)

Returns the square of the distance from a specified Point2D to this line.

26

double ptSegDist(double px, double py)

Returns the distance from a point to this line segment.

27

static double ptSegDist(double x1, double y1, double x2, double y2, double px, double py)

Returns the distance from a point to a line segment.

28

double ptSegDist(Point2D pt)

Returns the distance from a Point2D to this line segment.

29

double ptSegDistSq(double px, double py)

Returns the square of the distance from a point to this line segment.

30

static double ptSegDistSq(double x1, double y1, double x2, double y2, double px, double py)

Returns the square of the distance from a point to a line segment.

31

double ptSegDistSq(Point2D pt)

Returns the square of the distance from a Point2D to this line segment.

32

int relativeCCW(double px, double py)

Returns an indicator of where the specified point (px,py) lies with respect to this line segment.

33

static int relativeCCW(double x1, double y1, double x2, double y2, double px, double py)

Returns an indicator of where the specified point (px,py) lies with respect to the line segment from (x1,y1) to (x2,y2).

34

int relativeCCW(Point2D p)

Returns an indicator of where the specified Point2D lies with respect to this line segment.

35

abstract void setLine(double x1, double y1, double x2, double y2)

Sets the location of the end points of this Line2D to the specified double coordinates.

36

void setLine(Line2D l)

Sets the location of the end points of this Line2D to the same as those end points of the specified Line2D.

37

void setLine(Point2D p1, Point2D p2)

Sets the location of the end points of this Line2D to the specified Point2D coordinates.

Object clone()

Creates a new object of the same class as this object.

boolean contains(double x, double y)

Tests if a specified coordinate is inside the boundary of this Line2D.

boolean contains(double x, double y, double w, double h)

Tests if the interior of this Line2D entirely contains the specified set of rectangular coordinates.

boolean contains(Point2D p)

Tests if a given Point2D is inside the boundary of this Line2D.

boolean contains(Rectangle2D r)

Tests if the interior of this Line2D entirely contains the specified Rectangle2D.

Rectangle getBounds()

Returns an integer Rectangle that completely encloses the Shape.

abstract Point2D getP1()

Returns the start Point2D of this Line2D.

abstract Point2D getP2()

Returns the end Point2D of this Line2D.

PathIterator getPathIterator(AffineTransform at)

Returns an iteration object that defines the boundary of this Line2D.

PathIterator getPathIterator(AffineTransform at, double flatness)

Returns an iteration object that defines the boundary of this flattened Line2D.

abstract double getX1()

Returns the X coordinate of the start point in double precision.

abstract double getX2()

Returns the X coordinate of the end point in double precision.

abstract double getY1()

Returns the Y coordinate of the start point in double precision.

abstract double getY2()

Returns the Y coordinate of the end point in double precision.

boolean intersects(double x, double y, double w, double h)

Tests if the interior of the Shape intersects the interior of a specified rectangular area.

boolean intersects(Rectangle2D r)

Tests if the interior of the Shape intersects the interior of a specified Rectangle2D.

boolean intersectsLine(double x1, double y1, double x2, double y2)

Tests if the line segment from (x1,y1) to (x2,y2) intersects this line segment.

boolean intersectsLine(Line2D l)

Tests if the specified line segment intersects this line segment.

static boolean linesIntersect(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4)

Tests if the line segment from (x1,y1) to (x2,y2) intersects the line segment from (x3,y3) to (x4,y4).

double ptLineDist(double px, double py)

Returns the distance from a point to this line.

static double ptLineDist(double x1, double y1, double x2, double y2, double px, double py)

Returns the distance from a point to a line.

double ptLineDist(Point2D pt)

Returns the distance from a Point2D to this line.

double ptLineDistSq(double px, double py)

Returns the square of the distance from a point to this line.

static double ptLineDistSq(double x1, double y1, double x2, double y2, double px, double py)

Returns the square of the distance from a point to a line.

double ptLineDistSq(Point2D pt)

Returns the square of the distance from a specified Point2D to this line.

double ptSegDist(double px, double py)

Returns the distance from a point to this line segment.

static double ptSegDist(double x1, double y1, double x2, double y2, double px, double py)

Returns the distance from a point to a line segment.

double ptSegDist(Point2D pt)

Returns the distance from a Point2D to this line segment.

double ptSegDistSq(double px, double py)

Returns the square of the distance from a point to this line segment.

static double ptSegDistSq(double x1, double y1, double x2, double y2, double px, double py)

Returns the square of the distance from a point to a line segment.

double ptSegDistSq(Point2D pt)

Returns the square of the distance from a Point2D to this line segment.

int relativeCCW(double px, double py)

Returns an indicator of where the specified point (px,py) lies with respect to this line segment.

static int relativeCCW(double x1, double y1, double x2, double y2, double px, double py)

Returns an indicator of where the specified point (px,py) lies with respect to the line segment from (x1,y1) to (x2,y2).

int relativeCCW(Point2D p)

Returns an indicator of where the specified Point2D lies with respect to this line segment.

abstract void setLine(double x1, double y1, double x2, double y2)

Sets the location of the end points of this Line2D to the specified double coordinates.

void setLine(Line2D l)

Sets the location of the end points of this Line2D to the same as those end points of the specified Line2D.

void setLine(Point2D p1, Point2D p2)

Sets the location of the end points of this Line2D to the specified Point2D coordinates.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.lang.Object

java.lang.Object

Line2D Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AWTGraphicsDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

public class AWTGraphicsDemo extends Frame {
       
   public AWTGraphicsDemo(){
      super("Java AWT Examples");
      prepareGUI();
   }

   public static void main(String[] args){
      AWTGraphicsDemo  awtGraphicsDemo = new AWTGraphicsDemo();  
      awtGraphicsDemo.setVisible(true);
   }

   private void prepareGUI(){
      setSize(400,400);
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      }); 
   }    

   @Override
   public void paint(Graphics g) {
      Line2D shape = new Line2D.Double();
      shape.setLine(250D,250D,150D,150D);  
      Graphics2D g2 = (Graphics2D) g; 
      g2.draw (shape);
      Font font = new Font("Serif", Font.PLAIN, 24);
      g2.setFont(font);
      g.drawString("Welcome to TutorialsPoint", 50, 70);
      g2.drawString("Line2D.Line", 100, 120);  
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AWTGraphicsDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo

Проверьте следующий вывод

AWT Line2D

AWT Font Class

Вступление

The Font class states fonts, which are used to render text in a visible way.

Объявление класса

Following is the declaration for java.awt.Font class:

public class Font
   extends Object
      implements Serializable

поле

Following are the fields for java.awt.geom.Arc2D class:

  • static int BOLD — The bold style constant.

  • static int CENTER_BASELINE –The baseline used in ideographic scripts like Chinese, Japanese, and Korean when laying out text.

  • static String DIALOG –A String constant for the canonical family name of the logical font “Dialog”.

  • static String DIALOG_INPUT –A String constant for the canonical family name of the logical font “DialogInput”.

  • static int HANGING_BASELINE — The baseline used in Devanigiri and similar scripts when laying out text.

  • static int ITALIC — The italicized style constant.

  • static int LAYOUT_LEFT_TO_RIGHT — A flag to layoutGlyphVector indicating that text is left-to-right as determined by Bidi analysis.

  • static int LAYOUT_NO_LIMIT_CONTEXT — A flag to layoutGlyphVector indicating that text in the char array after the indicated limit should not be examined.

  • static int LAYOUT_NO_START_CONTEXT — A flag to layoutGlyphVector indicating that text in the char array before the indicated start should not be examined.

  • static int LAYOUT_RIGHT_TO_LEFT — A flag to layoutGlyphVector indicating that text is right-to-left as determined by Bidi analysis.

  • static String MONOSPACED — A String constant for the canonical family name of the logical font “Monospaced”.

  • protected String name — The logical name of this Font, as passed to the constructor.

  • static int PLAIN –The plain style constant.

  • protected float pointSize — The point size of this Font in float.

  • static int ROMAN_BASELINE –The baseline used in most Roman scripts when laying out text.

  • static String SANS_SERIF — A String constant for the canonical family name of the logical font “SansSerif”.

  • static String SERIF — A String constant for the canonical family name of the logical font “Serif”.

  • protected int size –The point size of this Font, rounded to integer.

  • protected int style — The style of this Font, as passed to the constructor.

  • static int TRUETYPE_FONT — Identify a font resource of type TRUETYPE.

  • static int TYPE1_FONT — Identify a font resource of type TYPE1.

static int BOLD — The bold style constant.

static int CENTER_BASELINE –The baseline used in ideographic scripts like Chinese, Japanese, and Korean when laying out text.

static String DIALOG –A String constant for the canonical family name of the logical font “Dialog”.

static String DIALOG_INPUT –A String constant for the canonical family name of the logical font “DialogInput”.

static int HANGING_BASELINE — The baseline used in Devanigiri and similar scripts when laying out text.

static int ITALIC — The italicized style constant.

static int LAYOUT_LEFT_TO_RIGHT — A flag to layoutGlyphVector indicating that text is left-to-right as determined by Bidi analysis.

static int LAYOUT_NO_LIMIT_CONTEXT — A flag to layoutGlyphVector indicating that text in the char array after the indicated limit should not be examined.

static int LAYOUT_NO_START_CONTEXT — A flag to layoutGlyphVector indicating that text in the char array before the indicated start should not be examined.

static int LAYOUT_RIGHT_TO_LEFT — A flag to layoutGlyphVector indicating that text is right-to-left as determined by Bidi analysis.

static String MONOSPACED — A String constant for the canonical family name of the logical font “Monospaced”.

protected String name — The logical name of this Font, as passed to the constructor.

static int PLAIN –The plain style constant.

protected float pointSize — The point size of this Font in float.

static int ROMAN_BASELINE –The baseline used in most Roman scripts when laying out text.

static String SANS_SERIF — A String constant for the canonical family name of the logical font “SansSerif”.

static String SERIF — A String constant for the canonical family name of the logical font “Serif”.

protected int size –The point size of this Font, rounded to integer.

protected int style — The style of this Font, as passed to the constructor.

static int TRUETYPE_FONT — Identify a font resource of type TRUETYPE.

static int TYPE1_FONT — Identify a font resource of type TYPE1.

Конструкторы классов

SN Конструктор и описание
1

protected Font() ()

Creates a new Font from the specified font.

2

Font(Map<? extends AttributedCharacterIterator.Attribute,?> attributes)

Creates a new Font from the specified font.

3

Font(String name, int style, int size)

Creates a new Font from the specified font.

protected Font() ()

Creates a new Font from the specified font.

Font(Map<? extends AttributedCharacterIterator.Attribute,?> attributes)

Creates a new Font from the specified font.

Font(String name, int style, int size)

Creates a new Font from the specified font.

Методы класса

SN Метод и описание
1

boolean canDisplay(char c)

Checks if this Font has a glyph for the specified character.

2

boolean canDisplay(int codePoint)

Checks if this Font has a glyph for the specified character.

3

int canDisplayUpTo(char[] text, int start, int limit)

Indicates whether or not this Font can display the characters in the specified text starting at start and ending at limit.

4

int canDisplayUpTo(CharacterIterator iter, int start, int limit)

Indicates whether or not this Font can display the text specified by the iter starting at start and ending at limit.

5

int canDisplayUpTo(String str)

Indicates whether or not this Font can display a specified String.

6

static Font createFont(int fontFormat, File fontFile)

Returns a new Font using the specified font type and the specified font file.

7

static Font createFont(int fontFormat, InputStream fontStream)

Returns a new Font using the specified font type and input data.

8

GlyphVector createGlyphVector(FontRenderContext frc, char[] chars)

Creates a GlyphVector by mapping characters to glyphs one-to-one based on the Unicode cmap in this Font.

9

GlyphVector createGlyphVector(FontRenderContext frc, CharacterIterator ci)

Creates a GlyphVector by mapping the specified characters to glyphs one-to-one based on the Unicode cmap in this Font.

10

GlyphVector createGlyphVector(FontRenderContext frc, int[] glyphCodes)

Creates a GlyphVector by mapping characters to glyphs one-to-one based on the Unicode cmap in this Font.

11

GlyphVector createGlyphVector(FontRenderContext frc, String str)

Creates a GlyphVector by mapping characters to glyphs one-to-one based on the Unicode cmap in this Font.

12

static Font decode(String str)

Returns the Font that the str argument describes.

13

Font deriveFont(AffineTransform trans)

Creates a new Font object by replicating the current Font object and applying a new transform to it.

14

Font deriveFont(float size)

Creates a new Font object by replicating the current Font object and applying a new size to it.

15

Font deriveFont(int style)

Creates a new Font object by replicating the current Font object and applying a new style to it.

16

Font deriveFont(int style, AffineTransform trans)

Creates a new Font object by replicating this Font object and applying a new style and transform.

17

Font deriveFont(int style, float size)

Creates a new Font object by replicating this Font object and applying a new style and size.

18

Font deriveFont(Map<? extends AttributedCharacterIterator.Attribute,?> attributes)

Creates a new Font object by replicating the current Font object and applying a new set of font attributes to it.

19

логическое равенство (Object obj)

Compares this Font object to the specified Object.

20

финал защищенный void ()

Disposes the native Font object.

21

Map<TextAttribute,?> getAttributes()

Returns a map of font attributes available in this Font.

22

AttributedCharacterIterator.Attribute[] getAvailableAttributes()

Returns the keys of all the attributes supported by this Font.

23

byte getBaselineFor(char c)

Returns the baseline appropriate for displaying this character.

24

String getFamily()

Returns the family name of this Font.

25

String getFamily(Locale l)

Returns the family name of this Font, localized for the specified locale.

26

static Font getFont(Map<? extends AttributedCharacterIterator.Attribute,?> attributes)

Returns a Font appropriate to the attributes.

27

static Font getFont(String nm)

Returns a Font object fom the system properties list.

28

static Font getFont(String nm, Font font)

Gets the specified Font from the system properties list.

29

String getFontName()

Returns the font face name of this Font.

30

String getFontName(Locale l)

Returns the font face name of the Font, localized for the specified locale.

31

float getItalicAngle()

Returns the italic angle of this Font.

32

LineMetrics getLineMetrics(char[] chars, int beginIndex, int limit, FontRenderContext frc)

Returns a LineMetrics object created with the specified arguments.

33

LineMetrics getLineMetrics(CharacterIterator ci, int beginIndex, int limit, FontRenderContext frc)

Returns a LineMetrics object created with the specified arguments.

34

LineMetrics getLineMetrics(String str, FontRenderContext frc)

Returns a LineMetrics object created with the specified String and FontRenderContext.

35

LineMetrics getLineMetrics(String str, int beginIndex, int limit, FontRenderContext frc)

Returns a LineMetrics object created with the specified arguments.

36

Rectangle2D getMaxCharBounds(FontRenderContext frc)

Returns the bounds for the character with the maximum bounds as defined in the specified FontRenderContext.

37

int getMissingGlyphCode()

Returns the glyphCode which is used when this Font does not have a glyph for a specified unicode code point.

38

Строка getName ()

Returns the logical name of this Font.

39

int getNumGlyphs()

Returns the number of glyphs in this Font.

40

java.awt.peer.FontPeer getPeer()

Устаревшее. Font rendering is now platform independent.

41

String getPSName()

Returns the postscript name of this Font.

42

int getSize()

Returns the point size of this Font, rounded to an integer.

43

float getSize2D()

Returns the point size of this Font in float value.

44

Rectangle2D getStringBounds(char[] chars, int beginIndex, int limit, FontRenderContext frc)

Returns the logical bounds of the specified array of characters in the specified FontRenderContext.

45

Rectangle2D getStringBounds(CharacterIterator ci, int beginIndex, int limit, FontRenderContext frc)

Returns the logical bounds of the characters indexed in the specified CharacterIterator in the specified FontRenderContext.

46

Rectangle2D getStringBounds(String str, FontRenderContext frc)

Returns the logical bounds of the specified String in the specified FontRenderContext.

47

Rectangle2D getStringBounds(String str, int beginIndex, int limit, FontRenderContext frc)

Returns the logical bounds of the specified String in the specified FontRenderContext.

48

int getStyle()

Returns the style of this Font.

49

AffineTransform getTransform()

Returns a copy of the transform associated with this Font.

50

int hashCode ()

Returns a hashcode for this Font.

51

boolean hasLayoutAttributes()

Return true if this Font contains attributes that require extra layout processing.

52

boolean hasUniformLineMetrics()

Checks whether or not this Font has uniform line metrics.

53

boolean isBold()

Indicates whether or not this Font object’s style is BOLD.

54

boolean isItalic()

Indicates whether or not this Font object’s style is ITALIC.

55

boolean isPlain()

Indicates whether or not this Font object’s style is PLAIN.

56

boolean isTransformed()

Indicates whether or not this Font object has a transform that affects its size in addition to the Size attribute.

57

GlyphVector layoutGlyphVector(FontRenderContext frc, char[] text, int start, int limit, int flags)

Returns a new GlyphVector object, performing full layout of the text if possible.

58

Строка toString ()

Converts this Font object to a String representation.

boolean canDisplay(char c)

Checks if this Font has a glyph for the specified character.

boolean canDisplay(int codePoint)

Checks if this Font has a glyph for the specified character.

int canDisplayUpTo(char[] text, int start, int limit)

Indicates whether or not this Font can display the characters in the specified text starting at start and ending at limit.

int canDisplayUpTo(CharacterIterator iter, int start, int limit)

Indicates whether or not this Font can display the text specified by the iter starting at start and ending at limit.

int canDisplayUpTo(String str)

Indicates whether or not this Font can display a specified String.

static Font createFont(int fontFormat, File fontFile)

Returns a new Font using the specified font type and the specified font file.

static Font createFont(int fontFormat, InputStream fontStream)

Returns a new Font using the specified font type and input data.

GlyphVector createGlyphVector(FontRenderContext frc, char[] chars)

Creates a GlyphVector by mapping characters to glyphs one-to-one based on the Unicode cmap in this Font.

GlyphVector createGlyphVector(FontRenderContext frc, CharacterIterator ci)

Creates a GlyphVector by mapping the specified characters to glyphs one-to-one based on the Unicode cmap in this Font.

GlyphVector createGlyphVector(FontRenderContext frc, int[] glyphCodes)

Creates a GlyphVector by mapping characters to glyphs one-to-one based on the Unicode cmap in this Font.

GlyphVector createGlyphVector(FontRenderContext frc, String str)

Creates a GlyphVector by mapping characters to glyphs one-to-one based on the Unicode cmap in this Font.

static Font decode(String str)

Returns the Font that the str argument describes.

Font deriveFont(AffineTransform trans)

Creates a new Font object by replicating the current Font object and applying a new transform to it.

Font deriveFont(float size)

Creates a new Font object by replicating the current Font object and applying a new size to it.

Font deriveFont(int style)

Creates a new Font object by replicating the current Font object and applying a new style to it.

Font deriveFont(int style, AffineTransform trans)

Creates a new Font object by replicating this Font object and applying a new style and transform.

Font deriveFont(int style, float size)

Creates a new Font object by replicating this Font object and applying a new style and size.

Font deriveFont(Map<? extends AttributedCharacterIterator.Attribute,?> attributes)

Creates a new Font object by replicating the current Font object and applying a new set of font attributes to it.

логическое равенство (Object obj)

Compares this Font object to the specified Object.

финал защищенный void ()

Disposes the native Font object.

Map<TextAttribute,?> getAttributes()

Returns a map of font attributes available in this Font.

AttributedCharacterIterator.Attribute[] getAvailableAttributes()

Returns the keys of all the attributes supported by this Font.

byte getBaselineFor(char c)

Returns the baseline appropriate for displaying this character.

String getFamily()

Returns the family name of this Font.

String getFamily(Locale l)

Returns the family name of this Font, localized for the specified locale.

static Font getFont(Map<? extends AttributedCharacterIterator.Attribute,?> attributes)

Returns a Font appropriate to the attributes.

static Font getFont(String nm)

Returns a Font object fom the system properties list.

static Font getFont(String nm, Font font)

Gets the specified Font from the system properties list.

String getFontName()

Returns the font face name of this Font.

String getFontName(Locale l)

Returns the font face name of the Font, localized for the specified locale.

float getItalicAngle()

Returns the italic angle of this Font.

LineMetrics getLineMetrics(char[] chars, int beginIndex, int limit, FontRenderContext frc)

Returns a LineMetrics object created with the specified arguments.

LineMetrics getLineMetrics(CharacterIterator ci, int beginIndex, int limit, FontRenderContext frc)

Returns a LineMetrics object created with the specified arguments.

LineMetrics getLineMetrics(String str, FontRenderContext frc)

Returns a LineMetrics object created with the specified String and FontRenderContext.

LineMetrics getLineMetrics(String str, int beginIndex, int limit, FontRenderContext frc)

Returns a LineMetrics object created with the specified arguments.

Rectangle2D getMaxCharBounds(FontRenderContext frc)

Returns the bounds for the character with the maximum bounds as defined in the specified FontRenderContext.

int getMissingGlyphCode()

Returns the glyphCode which is used when this Font does not have a glyph for a specified unicode code point.

Строка getName ()

Returns the logical name of this Font.

int getNumGlyphs()

Returns the number of glyphs in this Font.

java.awt.peer.FontPeer getPeer()

Устаревшее. Font rendering is now platform independent.

String getPSName()

Returns the postscript name of this Font.

int getSize()

Returns the point size of this Font, rounded to an integer.

float getSize2D()

Returns the point size of this Font in float value.

Rectangle2D getStringBounds(char[] chars, int beginIndex, int limit, FontRenderContext frc)

Returns the logical bounds of the specified array of characters in the specified FontRenderContext.

Rectangle2D getStringBounds(CharacterIterator ci, int beginIndex, int limit, FontRenderContext frc)

Returns the logical bounds of the characters indexed in the specified CharacterIterator in the specified FontRenderContext.

Rectangle2D getStringBounds(String str, FontRenderContext frc)

Returns the logical bounds of the specified String in the specified FontRenderContext.

Rectangle2D getStringBounds(String str, int beginIndex, int limit, FontRenderContext frc)

Returns the logical bounds of the specified String in the specified FontRenderContext.

int getStyle()

Returns the style of this Font.

AffineTransform getTransform()

Returns a copy of the transform associated with this Font.

int hashCode ()

Returns a hashcode for this Font.

boolean hasLayoutAttributes()

Return true if this Font contains attributes that require extra layout processing.

boolean hasUniformLineMetrics()

Checks whether or not this Font has uniform line metrics.

boolean isBold()

Indicates whether or not this Font object’s style is BOLD.

boolean isItalic()

Indicates whether or not this Font object’s style is ITALIC.

boolean isPlain()

Indicates whether or not this Font object’s style is PLAIN.

boolean isTransformed()

Indicates whether or not this Font object has a transform that affects its size in addition to the Size attribute.

GlyphVector layoutGlyphVector(FontRenderContext frc, char[] text, int start, int limit, int flags)

Returns a new GlyphVector object, performing full layout of the text if possible.

Строка toString ()

Converts this Font object to a String representation.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.lang.Object

java.lang.Object

Font Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AWTGraphicsDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

public class AWTGraphicsDemo extends Frame {
       
   public AWTGraphicsDemo(){
      super("Java AWT Examples");
      prepareGUI();
   }

   public static void main(String[] args){
      AWTGraphicsDemo  awtGraphicsDemo = new AWTGraphicsDemo();  
      awtGraphicsDemo.setVisible(true);
   }

   private void prepareGUI(){
      setSize(400,400);
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      }); 
   }    

   @Override
   public void paint(Graphics g) {
      Graphics2D g2 = (Graphics2D)g;        
      Font plainFont = new Font("Serif", Font.PLAIN, 24);        
      g2.setFont(plainFont);
      g2.drawString("Welcome to TutorialsPoint", 50, 70); 
      Font italicFont = new Font("Serif", Font.ITALIC, 24);        
      g2.setFont(italicFont);
      g2.drawString("Welcome to TutorialsPoint", 50, 120); 
      Font boldFont = new Font("Serif", Font.BOLD, 24);        
      g2.setFont(boldFont);
      g2.drawString("Welcome to TutorialsPoint", 50, 170); 
      Font boldItalicFont = new Font("Serif", Font.BOLD+Font.ITALIC, 24);        
      g2.setFont(boldItalicFont);
      g2.drawString("Welcome to TutorialsPoint", 50, 220); 
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AWTGraphicsDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo

Проверьте следующий вывод

AWT Font

AWT Color Class

Вступление

The Color class states colors in the default sRGB color space or colors in arbitrary color spaces identified by a ColorSpace.

Объявление класса

Following is the declaration for java.awt.Color class:

public class Color
   extends Object
      implements Paint, Serializable

поле

Following are the fields for java.awt.geom.Arc2D class:

  • static Color black — The color black.

  • static Color BLACK — The color black.

  • static Color blue — The color blue.

  • static Color BLUE — The color blue.

  • static Color cyan — The color cyan.

  • static Color CYAN — The color cyan.

  • static Color DARK_GRAY — The color dark gray.

  • static Color darkGray — The color dark gray.

  • static Color gray — The color gray.

  • static Color GRAY — The color gray.

  • static Color green — The color green.

  • static Color GREEN — The color green.

  • static Color LIGHT_GRAY — The color light gray.

  • static Color lightGray — The color light gray.

  • static Color magenta — The color magenta.

  • static Color MAGENTA — The color magenta.

  • static Color orange — The color orange.

  • static Color ORANGE — The color orange.

  • static Color pink — The color pink.

  • static Color PINK — The color pink.

  • static Color red — The color red.

  • static Color RED — The color red.

  • static Color white — The color white.

  • static Color WHITE — The color white.

  • static Color yellow — The color yellow.

  • static Color YELLOW — The color yellow.

static Color black — The color black.

static Color BLACK — The color black.

static Color blue — The color blue.

static Color BLUE — The color blue.

static Color cyan — The color cyan.

static Color CYAN — The color cyan.

static Color DARK_GRAY — The color dark gray.

static Color darkGray — The color dark gray.

static Color gray — The color gray.

static Color GRAY — The color gray.

static Color green — The color green.

static Color GREEN — The color green.

static Color LIGHT_GRAY — The color light gray.

static Color lightGray — The color light gray.

static Color magenta — The color magenta.

static Color MAGENTA — The color magenta.

static Color orange — The color orange.

static Color ORANGE — The color orange.

static Color pink — The color pink.

static Color PINK — The color pink.

static Color red — The color red.

static Color RED — The color red.

static Color white — The color white.

static Color WHITE — The color white.

static Color yellow — The color yellow.

static Color YELLOW — The color yellow.

Конструкторы классов

SN Конструктор и описание
1

Color(ColorSpace cspace, float[] components, float alpha)

Creates a color in the specified ColorSpace with the color components specified in the float array and the specified alpha.

2

Color(float r, float g, float b)

Creates an opaque sRGB color with the specified red, green, and blue values in the range (0.0 – 1.0).

3

Color(float r, float g, float b, float a)

Creates an sRGB color with the specified red, green, blue, and alpha values in the range (0.0 – 1.0).

4

Color(int rgb)

Creates an opaque sRGB color with the specified combined RGB value consisting of the red component in bits 16-23, the green component in bits 8-15, and the blue component in bits 0-7.

5

Color(int rgba, boolean hasalpha)

Creates an sRGB color with the specified combined RGBA value consisting of the alpha component in bits 24-31, the red component in bits 16-23, the green component in bits 8-15, and the blue component in bits 0-7.

6

Color(int r, int g, int b)

Creates an opaque sRGB color with the specified red, green, and blue values in the range (0 – 255).

7

Color(int r, int g, int b, int a)

Creates an sRGB color with the specified red, green, blue, and alpha values in the range (0 – 255).

Color(ColorSpace cspace, float[] components, float alpha)

Creates a color in the specified ColorSpace with the color components specified in the float array and the specified alpha.

Color(float r, float g, float b)

Creates an opaque sRGB color with the specified red, green, and blue values in the range (0.0 – 1.0).

Color(float r, float g, float b, float a)

Creates an sRGB color with the specified red, green, blue, and alpha values in the range (0.0 – 1.0).

Color(int rgb)

Creates an opaque sRGB color with the specified combined RGB value consisting of the red component in bits 16-23, the green component in bits 8-15, and the blue component in bits 0-7.

Color(int rgba, boolean hasalpha)

Creates an sRGB color with the specified combined RGBA value consisting of the alpha component in bits 24-31, the red component in bits 16-23, the green component in bits 8-15, and the blue component in bits 0-7.

Color(int r, int g, int b)

Creates an opaque sRGB color with the specified red, green, and blue values in the range (0 – 255).

Color(int r, int g, int b, int a)

Creates an sRGB color with the specified red, green, blue, and alpha values in the range (0 – 255).

Методы класса

SN Метод и описание
1

Color brighter()

Creates a new Color that is a brighter version of this Color.

2

PaintContext createContext(ColorModel cm, Rectangle r, Rectangle2D r2d, AffineTransform xform, RenderingHints hints)

Creates and returns a PaintContext used to generate a solid color pattern.

3

Color darker()

Creates a new Color that is a darker version of this Color.

4

static Color decode(String nm)

Converts a String to an integer and returns the specified opaque Color.

5

логическое равенство (Object obj)

Determines whether another object is equal to this Color.

6

int getAlpha()

Returns the alpha component in the range 0-255.

7

int getBlue()

Returns the blue component in the range 0-255 in the default sRGB space.

8

static Color getColor(String nm)

Finds a color in the system properties.

9

static Color getColor(String nm, Color v)

Finds a color in the system properties.

10

static Color getColor(String nm, int v)

Finds a color in the system properties.

11

float[] getColorComponents(ColorSpace cspace, float[] compArray)

Returns a float array containing only the color components of the Color in the ColorSpace specified by the cspace parameter.

12

float[] getColorComponents(float[] compArray)

Returns a float array containing only the color components of the Color, in the ColorSpace of the Color.

13

ColorSpace getColorSpace()

Returns the ColorSpace of this Color.

14

float[] getComponents(ColorSpace cspace, float[] compArray)

Returns a float array containing the color and alpha components of the Color, in the ColorSpace specified by the cspace parameter.

15

float[] getComponents(float[] compArray)

Returns a float array containing the color and alpha components of the Color, in the ColorSpace of the Color.

16

int getGreen()

Returns the green component in the range 0-255 in the default sRGB space.

17

static Color getHSBColor(float h, float s, float b)

Creates a Color object based on the specified values for the HSB color model.

18

int getRed()

Returns the red component in the range 0-255 in the default sRGB space.

19

int getRGB()

Returns the RGB value representing the color in the default sRGB ColorModel.

20

float[] getRGBColorComponents(float[] compArray)

Returns a float array containing only the color components of the Color, in the default sRGB color space.

21

float[] getRGBComponents(float[] compArray)

Returns a float array containing the color and alpha components of the Color, as represented in the default sRGB color space.

22

int getTransparency()

Returns the transparency mode for this Color.

23

int hashCode ()

Computes the hash code for this Color.

24

static int HSBtoRGB(float hue, float saturation, float brightness)

Converts the components of a color, as specified by the HSB model, to an equivalent set of values for the default RGB model.

25

static float[] RGBtoHSB(int r, int g, int b, float[] hsbvals)

Converts the components of a color, as specified by the default RGB model, to an equivalent set of values for hue, saturation, and brightness that are the three components of the HSB model.

26

Строка toString ()

Returns a string representation of this Color.

Color brighter()

Creates a new Color that is a brighter version of this Color.

PaintContext createContext(ColorModel cm, Rectangle r, Rectangle2D r2d, AffineTransform xform, RenderingHints hints)

Creates and returns a PaintContext used to generate a solid color pattern.

Color darker()

Creates a new Color that is a darker version of this Color.

static Color decode(String nm)

Converts a String to an integer and returns the specified opaque Color.

логическое равенство (Object obj)

Determines whether another object is equal to this Color.

int getAlpha()

Returns the alpha component in the range 0-255.

int getBlue()

Returns the blue component in the range 0-255 in the default sRGB space.

static Color getColor(String nm)

Finds a color in the system properties.

static Color getColor(String nm, Color v)

Finds a color in the system properties.

static Color getColor(String nm, int v)

Finds a color in the system properties.

float[] getColorComponents(ColorSpace cspace, float[] compArray)

Returns a float array containing only the color components of the Color in the ColorSpace specified by the cspace parameter.

float[] getColorComponents(float[] compArray)

Returns a float array containing only the color components of the Color, in the ColorSpace of the Color.

ColorSpace getColorSpace()

Returns the ColorSpace of this Color.

float[] getComponents(ColorSpace cspace, float[] compArray)

Returns a float array containing the color and alpha components of the Color, in the ColorSpace specified by the cspace parameter.

float[] getComponents(float[] compArray)

Returns a float array containing the color and alpha components of the Color, in the ColorSpace of the Color.

int getGreen()

Returns the green component in the range 0-255 in the default sRGB space.

static Color getHSBColor(float h, float s, float b)

Creates a Color object based on the specified values for the HSB color model.

int getRed()

Returns the red component in the range 0-255 in the default sRGB space.

int getRGB()

Returns the RGB value representing the color in the default sRGB ColorModel.

float[] getRGBColorComponents(float[] compArray)

Returns a float array containing only the color components of the Color, in the default sRGB color space.

float[] getRGBComponents(float[] compArray)

Returns a float array containing the color and alpha components of the Color, as represented in the default sRGB color space.

int getTransparency()

Returns the transparency mode for this Color.

int hashCode ()

Computes the hash code for this Color.

static int HSBtoRGB(float hue, float saturation, float brightness)

Converts the components of a color, as specified by the HSB model, to an equivalent set of values for the default RGB model.

static float[] RGBtoHSB(int r, int g, int b, float[] hsbvals)

Converts the components of a color, as specified by the default RGB model, to an equivalent set of values for hue, saturation, and brightness that are the three components of the HSB model.

Строка toString ()

Returns a string representation of this Color.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.lang.Object

java.lang.Object

Пример цвета

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AWTGraphicsDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

public class AWTGraphicsDemo extends Frame {
       
   public AWTGraphicsDemo(){
      super("Java AWT Examples");
      prepareGUI();
   }

   public static void main(String[] args){
      AWTGraphicsDemo  awtGraphicsDemo = new AWTGraphicsDemo();  
      awtGraphicsDemo.setVisible(true);
   }

   private void prepareGUI(){
      setSize(400,400);
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      }); 
   }    

   @Override
   public void paint(Graphics g) {
      Graphics2D g2 = (Graphics2D)g;        
      Font plainFont = new Font("Serif", Font.PLAIN, 24);        
      g2.setFont(plainFont);
      g2.setColor(Color.red);
      g2.drawString("Welcome to TutorialsPoint", 50, 70); 
      g2.setColor(Color.GRAY);
      g2.drawString("Welcome to TutorialsPoint", 50, 120);  
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AWTGraphicsDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo

Проверьте следующий вывод

AWT Color

AWT BasicStroke Class

Вступление

The BasicStroke class states colors in the default sRGB color space or colors in arbitrary color spaces identified by a ColorSpace.

Объявление класса

Following is the declaration for java.awt.BasicStroke class:

public class BasicStroke
   extends Object
      implements Stroke

поле

Following are the fields for java.awt.geom.Arc2D class:

  • static int CAP_BUTT — Ends unclosed subpaths and dash segments with no added decoration.

  • static int CAP_ROUND — Ends unclosed subpaths and dash segments with a round decoration that has a radius equal to half of the width of the pen.

  • static int CAP_SQUARE — Ends unclosed subpaths and dash segments with a square projection that extends beyond the end of the segment to a distance equal to half of the line width.

  • static int JOIN_BEVEL — Joins path segments by connecting the outer corners of their wide outlines with a straight segment.

  • static int JOIN_MITER — Joins path segments by extending their outside edges until they meet.

  • static int JOIN_ROUND — Joins path segments by rounding off the corner at a radius of half the line width.

static int CAP_BUTT — Ends unclosed subpaths and dash segments with no added decoration.

static int CAP_ROUND — Ends unclosed subpaths and dash segments with a round decoration that has a radius equal to half of the width of the pen.

static int CAP_SQUARE — Ends unclosed subpaths and dash segments with a square projection that extends beyond the end of the segment to a distance equal to half of the line width.

static int JOIN_BEVEL — Joins path segments by connecting the outer corners of their wide outlines with a straight segment.

static int JOIN_MITER — Joins path segments by extending their outside edges until they meet.

static int JOIN_ROUND — Joins path segments by rounding off the corner at a radius of half the line width.

Конструкторы классов

SN Конструктор и описание
1

BasicStroke()

Constructs a new BasicStroke with defaults for all attributes.

2

BasicStroke(float width)

Constructs a solid BasicStroke with the specified line width and with default values for the cap and join styles.

3

BasicStroke(float width, int cap, int join)

Constructs a solid BasicStroke with the specified attributes.

4

BasicStroke(float width, int cap, int join, float miterlimit)

Constructs a solid BasicStroke with the specified attributes.

5

BasicStroke(float width, int cap, int join, float miterlimit, float[] dash, float dash_phase)

Constructs a new BasicStroke with the specified attributes.

BasicStroke()

Constructs a new BasicStroke with defaults for all attributes.

BasicStroke(float width)

Constructs a solid BasicStroke with the specified line width and with default values for the cap and join styles.

BasicStroke(float width, int cap, int join)

Constructs a solid BasicStroke with the specified attributes.

BasicStroke(float width, int cap, int join, float miterlimit)

Constructs a solid BasicStroke with the specified attributes.

BasicStroke(float width, int cap, int join, float miterlimit, float[] dash, float dash_phase)

Constructs a new BasicStroke with the specified attributes.

Методы класса

SN Метод и описание
1

Shape createStrokedShape(Shape s)

Returns a Shape whose interior defines the stroked outline of a specified Shape.

2

логическое равенство (Object obj)

Tests if a specified object is equal to this BasicStroke by first testing if it is a BasicStroke and then comparing its width, join, cap, miter limit, dash, and dash phase attributes with those of this BasicStroke.

3

float[] getDashArray()

Returns the array representing the lengths of the dash segments.

4

float getDashPhase()

Returns the current dash phase.

5

int getEndCap()

Returns the end cap style.

6

int getLineJoin()

Returns the line join style.

7

float getLineWidth()

Returns the line width.

8

float getMiterLimit()

Returns the limit of miter joins.

9

int hashCode ()

Returns the hashcode for this stroke.

Shape createStrokedShape(Shape s)

Returns a Shape whose interior defines the stroked outline of a specified Shape.

логическое равенство (Object obj)

Tests if a specified object is equal to this BasicStroke by first testing if it is a BasicStroke and then comparing its width, join, cap, miter limit, dash, and dash phase attributes with those of this BasicStroke.

float[] getDashArray()

Returns the array representing the lengths of the dash segments.

float getDashPhase()

Returns the current dash phase.

int getEndCap()

Returns the end cap style.

int getLineJoin()

Returns the line join style.

float getLineWidth()

Returns the line width.

float getMiterLimit()

Returns the limit of miter joins.

int hashCode ()

Returns the hashcode for this stroke.

Методы унаследованы

Этот класс наследует методы от следующих классов:

  • java.lang.Object

java.lang.Object

BasicStroke Example

Создайте следующую Java-программу, используя любой редактор по вашему выбору, скажем, D: /> AWT> com> tutorialspoint> gui>

AWTGraphicsDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

public class AWTGraphicsDemo extends Frame {
       
   public AWTGraphicsDemo(){
      super("Java AWT Examples");
      prepareGUI();
   }

   public static void main(String[] args){
      AWTGraphicsDemo  awtGraphicsDemo = new AWTGraphicsDemo();  
      awtGraphicsDemo.setVisible(true);
   }

   private void prepareGUI(){
      setSize(400,400);
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      }); 
   }    

   @Override
   public void paint(Graphics g) {
      Graphics2D g2 = (Graphics2D)g;        
      g2.setStroke(new BasicStroke(3.0f));
      g2.setPaint(Color.blue);

      Rectangle2D shape = new Rectangle2D.Float();
      shape.setFrame(100, 150, 200,100);
      g2.draw(shape);

      Rectangle2D shape1 = new Rectangle2D.Float();
      shape1.setFrame(110, 160, 180,80);
      g2.setStroke(new BasicStroke(1.0f));
   
      g2.draw(shape1);
      Font plainFont = new Font("Serif", Font.PLAIN, 24);        
      g2.setFont(plainFont);
      g2.setColor(Color.DARK_GRAY);
      g2.drawString("TutorialsPoint", 130, 200);
   }
}

Скомпилируйте программу, используя командную строку. Перейдите к D: /> AWT и введите следующую команду.

D:\AWT>javac com\tutorialspoint\gui\AwtGraphicsDemo.java

Если нет ошибок, это означает, что компиляция прошла успешно. Запустите программу, используя следующую команду.

D:\AWT>java com.tutorialspoint.gui.AwtGraphicsDemo

Проверьте следующий вывод