Addwindowlistener java что это

Addwindowlistener java что это

A Window object is a top-level window with no borders and no menubar. The default layout for a window is BorderLayout . A window must have either a frame, dialog, or another window defined as its owner when it’s constructed. In a multi-screen environment, you can create a Window on a different screen device by constructing the Window with Window(Window, GraphicsConfiguration) . The GraphicsConfiguration object is one of the GraphicsConfiguration objects of the target screen device. In a virtual device multi-screen environment in which the desktop area could span multiple physical screen devices, the bounds of all configurations are relative to the virtual device coordinate system. The origin of the virtual-coordinate system is at the upper left-hand corner of the primary physical screen. Depending on the location of the primary screen in the virtual device, negative coordinates are possible, as shown in the following figure. In such an environment, when calling setLocation , you must pass a virtual coordinate to this method. Similarly, calling getLocationOnScreen on a Window returns virtual device coordinates. Call the getBounds method of a GraphicsConfiguration to find its origin in the virtual coordinate system. The following code sets the location of a Window at (10, 10) relative to the origin of the physical screen of the corresponding GraphicsConfiguration . If the bounds of the GraphicsConfiguration is not taken into account, the Window location would be set at (10, 10) relative to the virtual-coordinate system and would appear on the primary physical screen, which might be different from the physical screen of the specified GraphicsConfiguration .

Window w = new Window(Window owner, GraphicsConfiguration gc); Rectangle bounds = gc.getBounds(); w.setLocation(10 + bounds.x, 10 + bounds.y);

Note: the location and size of top-level windows (including Window s, Frame s, and Dialog s) are under the control of the desktop’s window management system. Calls to setLocation , setSize , and setBounds are requests (not directives) which are forwarded to the window management system. Every effort will be made to honor such requests. However, in some cases the window management system may ignore such requests, or modify the requested geometry in order to place and size the Window in a way that more closely matches the desktop settings. Due to the asynchronous nature of native event handling, the results returned by getBounds , getLocation , getLocationOnScreen , and getSize might not reflect the actual geometry of the Window on screen until the last request has been processed. During the processing of subsequent requests these values might change accordingly while the window management system fulfills the requests. An application may set the size and location of an invisible Window arbitrarily, but the window management system may subsequently change its size and/or location when the Window is made visible. One or more ComponentEvent s will be generated to indicate the new geometry. Windows are capable of generating the following WindowEvents: WindowOpened, WindowClosed, WindowGainedFocus, WindowLostFocus.

Читайте также:  Addy osmani javascript design pattern

Nested Class Summary

Источник

Слушаем оконные события JFrame

JFrame в Java Swing при определенном взаимодействии с пользователем (свернуть, развернуть, открыть, закрыть) информирует систему о наступлении оконных Window событий. На самом деле я не знаю, как правильно назвать события, которые возникают, когда пользователь сворачивает, разворачивает, открывает и закрывает окно JFrame. Думаю, что по смыслу подходит название «оконные». Временами разработчику нужно каким-то образом реагировать на такие события. Как это сделать? Следуя философии Java Swing нам нужно отыскать интерфейс нужного слушателя listener’а, который может прослушивать события такого вида. Таким интерфейсом слушателя является WindowListener. Этот интерфейс расположен в пакете java.awt.event и имеет несколько методов. Методы рассмотрим чуть ниже. Далее мы должны реализовать этот интерфейс и полученного слушателя добавить к JFrame.

Рассмотрим методы, которые необходимо реализовать. Напомню, что реализовать мы должны все методы WindowListener, но никто не запрещает нам оставить реализации пустыми, ведь не всегда же нам нужно реагировать на всё происходящее. Совсем как в жизни, если на всё реагировать, то с ума можно сойти 🙂 Первый метод – это windowActivated. Данный метод у слушателя будет вызываться каждый раз, когда окно будет становиться активным. Например, у нас есть два окна – окно нашего приложения и другое. Если переключиться на окно другого приложения, а затем на наше – то непременно произойдет вызов метода windowActivated. Далее метод windowClosed. Метод интересный, потому что судя по документации вызываться он будет только если мы скажем JFrame сделать dispose, то есть очистить все нативные ресурсы. Для этого в JFrame есть специальный метод, который так и называется dispose. Если закрывать окно на крестик в правой части заголовка, то метод вызываться не будет. Тогда как же узнать, что пользователь всё-таки нажал на «Закрыть» у JFrame’а ? Как только кликаем крестик, вызывается метод windowClosing. Следующий метод в списке – это windowDeactivated. Думаю из названия этого метода понятно, что вызывается он в тот момент, когда окно нашего приложения перестает быть активным, то есть мы просто переключаемся на другое окно. При сворачивании и разворачивании окна приложения будут вызываться методы windowIconified и windowDeiconified соответственно. Ну и последний метод windowOpened. Вызывается у слушателя как только окно открывается, точнее после того как окно открылось.

Читайте также:  Javascript button onclick this form

Как только слушатель создан, можно приступить к его добавлению к JFrame. Делается это при помощи методы addWindowListener. В качестве параметра передается ссылка на экземпляр слушателя, реализующего WindowListener.

По традиции простой пример. Здесь мы создаем окно приложения JFrame и еще один класс, который реализует интерфейс WindowListener. Этот класс TestWindowListener далее используется для создания слушателя, который добавляется к JFrame. Все результаты работы приложения выводятся в консоль. Так очень легко можно проследить последовательность вызова методов у слушателя при срабатывании оконных событий. Внешний вид приложения и исходный код представлены ниже.

simple_jframe

import java.awt.Dimension;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

public class TestFrame extends JFrame

public static void createGUI() JFrame frame = new JFrame(«Test frame»);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

WindowListener winListener = new TestWindowListener();
frame.addWindowListener(winListener);

frame.setPreferredSize(new Dimension(450, 200));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
>

public static void main(String[] args) javax.swing.SwingUtilities.invokeLater(new Runnable() public void run() JFrame.setDefaultLookAndFeelDecorated(true);
createGUI();
>
>);
>

public static class TestWindowListener implements WindowListener

public void windowActivated(WindowEvent e) System.out.println(«windowActivated()»);
>

public void windowClosed(WindowEvent e) System.out.println(«windowClosed()»);
>

public void windowClosing(WindowEvent e) System.out.println(«windowClosing()»);
>

public void windowDeactivated(WindowEvent e) System.out.println(«windowDeactivated()»);
>

public void windowDeiconified(WindowEvent e) System.out.println(«windowDeiconified()»);
>

public void windowIconified(WindowEvent e) System.out.println(«windowIconified()»);
>

public void windowOpened(WindowEvent e) System.out.println(«windowOpened()»);
>
>
>

Источник

Class Window

A Window object is a top-level window with no borders and no menubar. The default layout for a window is BorderLayout .

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

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

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

Читайте также:  Html font color size align

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

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

Window w = new Window(Window owner, GraphicsConfiguration gc); Rectangle bounds = gc.getBounds(); w.setLocation(10 + bounds.x, 10 + bounds.y);

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

Visual effects such as halos, shadows, motion effects and animations may be applied to the window by the desktop window management system. These are outside the knowledge and control of the AWT and so for the purposes of this specification are not considered part of the top-level window.

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

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

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

Источник

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