Java Open a Dialog Again Until Condition Is Met

This section explains how to implement three kinds of window-related event handlers: WindowListener, WindowFocusListener, and WindowStateListener. All iii listeners handle WindowEvent objects. The methods in all three event handlers are implemented by the abstract WindowAdapter class.

When the advisable listener has been registered on a window (such as a frame or dialog), window events are fired just afterward the window activity or state has occurred. A window is considered every bit a "focus owner", if this window receives keyboard input.

The post-obit window activities or states tin can precede a window event:

  • Opening a window — Showing a window for the first time.
  • Closing a window — Removing the window from the screen.
  • Iconifying a window — Reducing the window to an icon on the desktop.
  • Deiconifying a window — Restoring the window to its original size.
  • Focused window — The window which contains the "focus possessor".
  • Activated window (frame or dialog) — This window is either the focused window, or owns the focused window.
  • Deactivated window — This window has lost the focus. For more information about focus, see the AWT Focus Subsystem specification.
  • Maximizing the window — Increasing a window'due south size to the maximum commanded size, either in the vertical direction, the horizontal direction, or both directions.

    The WindowListener interface defines methods that handle virtually window events, such as the events for opening and closing the window, activation and deactivation of the window, and iconification and deiconification of the window.

    The other two window listener interfaces are WindowFocusListener and WindowStateListener. WindowFocusListener contains methods to observe when the window becomes the focus possessor or it loses the focus owner condition. WindowStateListener has a single method to detect a change to the land of the window, such every bit when the window is iconified, deiconified, maximized, or restored to normal.

    While you lot can utilise the WindowListener methods to observe some window states, such as iconification, there are two reasons why a WindowStateListener might be preferable: information technology has only ane method for you lot to implement, and it provides support for maximization.


    Note: Non all window managers/native platforms support all window states. The coffee.awt.Toolkit method isFrameStateSupported(int) can be used to determine whether a particular window state is supported by a item window director. The WindowEventDemo example, described later in this section, shows how this method can be used.


    Window listeners are normally used to implement custom window-closing beliefs. For example, a window listener is used to save data before closing the window, or to get out the program when the last window closes.

    A user does not necessarily need to implement a window listener to specify what a window should exercise when the user closes it. By default, when the user closes a window the window becomes invisible. To specify different behavior, utilize the setDefaultCloseOperation method of the JFrame or JDialog classes. To implement a window-closing handler, use the setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE) method to enable the window listener to provide all window-closing duties. Come across Responding to Window-Endmost Events for details on how to use setDefaultCloseOperation.

    When the terminal displayable window within the Coffee virtual machine (VM) is tending of, the VM may cease. Annotation, withal, that there can be a delay earlier the program exits automatically, and that under some circumstances the program might keep running. It is quicker and safer to explicitly exit the programme using System.leave(int). Come across AWT Threading Issues for more information.

    Window listeners are likewise commonly used to stop threads and release resource when a window is iconified, and to start up again when the window is deiconified. This avoids unnecessarily using the processor or other resources. For case, when a window that contains animation is iconified, it should end its animation thread and free whatever large buffers. When the window is deiconified, information technology can start the thread again and recreate the buffers.

    The following example demonstrates window events. A non-editable text expanse reports all window events that are fired past its window. This demo implements all methods in the WindowListener, WindowFocusListener, and WindowStateListener interfaces. You lot tin notice the demo's code in WindowEventDemo.java.

    WindowEventDemo.html

    Try this:

    1. Click the Launch push to run WindowEventDemo using Java™ Web Start (download JDK seven or later). Alternatively, to compile and run the example yourself, consult the example index.Launches the WindowEventDemo application
    2. When the window appears, several messages are already displayed. One line reports whether your window director supports MAXIMIZED_BOTH. If the window managing director does not support other window states, this status is too reported. Next, several lines are displayed, reporting that the window's window listener has received window-opened, activated, and gained-focus events. All the messages displayed in the window are besides sent to standard output.
    3. Click another window. The "window lost focus" and "window deactivated" messages will be displayed. If this window is not a frame or a dialog, information technology will receive the activated or deactivated events.
    4. Click the WindowEventDemo window. You'll see "window activated" and "window gained focus" messages.
    5. Iconify the window, using the window controls. 2 iconification letters are displayed, one from the window listener and the other from the window country listener. Unless you are looking at standard output, the messages will not display until the window is deiconified. Window-deactivation and window-lost-focus events are too reported.
    6. De-iconify the window. Two deiconification messages are displayed, one from the window listener and the other from the window state listener. The windowStateChanged method in WindowStateListener course gives the same information that you go using the windowIconified and windowDeiconified methods in WindowListener class. Window-activation and window-gained-focus events are as well reported.
    7. Maximize the window, if your await and experience provides a way to do so. Notation that some look and feels running on some window managers, such equally the Java look and feel on dtwm, provide a way to maximize the window, but no events are reported. This is because dtwm mimics maximization past resizing the window, simply it is not a truthful maximization outcome. Some look and feels provide a way to maximize the window in the vertical or horizontal direction but. Experiment with your window controls to run into what options are available.
    8. Close the window, using the window controls. A window closing message is displayed. Once the window has airtight, a window closed bulletin is sent to standard output.

    Hither is the demo's window event handling code:

    public class WindowEventDemo extends JFrame implements WindowListener,                                             WindowFocusListener,                                             WindowStateListener {     ...     static WindowEventDemo frame = new WindowEventDemo("WindowEventDemo");     JTextArea display;     ...      private void addComponentsToPane() {         display = new JTextArea();         display.setEditable(fake);         JScrollPane scrollPane = new JScrollPane(display);         scrollPane.setPreferredSize(new Dimension(500, 450));         getContentPane().add(scrollPane, BorderLayout.Eye);                  addWindowListener(this);         addWindowFocusListener(this);         addWindowStateListener(this);                  checkWM();     }          public WindowEventDemo(Cord proper name) {         super(name);     }      //Some window managers don't support all window states.        public void checkWM() {         Toolkit tk = frame.getToolkit();         if (!(tk.isFrameStateSupported(Frame.ICONIFIED))) {             displayMessage(                     "Your window manager doesn't support ICONIFIED.");         }  else displayMessage(                 "Your window manager supports ICONIFIED.");         if (!(tk.isFrameStateSupported(Frame.MAXIMIZED_VERT))) {             displayMessage(                     "Your window managing director doesn't support MAXIMIZED_VERT.");         }  else displayMessage(                 "Your window manager supports MAXIMIZED_VERT.");         if (!(tk.isFrameStateSupported(Frame.MAXIMIZED_HORIZ))) {             displayMessage(                     "Your window manager doesn't support MAXIMIZED_HORIZ.");         } else displayMessage(                 "Your window manager supports MAXIMIZED_HORIZ.");         if (!(tk.isFrameStateSupported(Frame.MAXIMIZED_BOTH))) {             displayMessage(                     "Your window manager doesn't support MAXIMIZED_BOTH.");         } else {             displayMessage(                     "Your window manager supports MAXIMIZED_BOTH.");         }     }      public void windowClosing(WindowEvent due east) {         displayMessage("WindowListener method called: windowClosing.");         //A pause so user tin run across the message before         //the window actually closes.         ActionListener task = new ActionListener() {             boolean alreadyDisposed = imitation;             public void actionPerformed(ActionEvent e) {                 if (frame.isDisplayable()) {                     alreadyDisposed = true;                     frame.dispose();                 }             }         };         Timer timer = new Timer(500, job); //burn down every half 2d         timer.setInitialDelay(2000);        //start delay 2 seconds         timer.setRepeats(false);         timer.start();     }      public void windowClosed(WindowEvent e) {         //This will only be seen on standard output.         displayMessage("WindowListener method called: windowClosed.");     }      public void windowOpened(WindowEvent e) {         displayMessage("WindowListener method called: windowOpened.");     }      public void windowIconified(WindowEvent e) {         displayMessage("WindowListener method chosen: windowIconified.");     }      public void windowDeiconified(WindowEvent due east) {         displayMessage("WindowListener method called: windowDeiconified.");     }      public void windowActivated(WindowEvent e) {         displayMessage("WindowListener method called: windowActivated.");     }      public void windowDeactivated(WindowEvent e) {         displayMessage("WindowListener method called: windowDeactivated.");     }      public void windowGainedFocus(WindowEvent e) {         displayMessage("WindowFocusListener method called: windowGainedFocus.");     }      public void windowLostFocus(WindowEvent e) {         displayMessage("WindowFocusListener method called: windowLostFocus.");     }      public void windowStateChanged(WindowEvent eastward) {         displayStateMessage(           "WindowStateListener method called: windowStateChanged.", due east);     }      void displayMessage(String msg) {         display.suspend(msg + newline);         Arrangement.out.println(msg);     }      void displayStateMessage(Cord prefix, WindowEvent e) {         int state = e.getNewState();         int oldState = eastward.getOldState();         Cord msg = prefix                    + newline + space                    + "New state: "                    + convertStateToString(state)                    + newline + space                    + "Old state: "                    + convertStateToString(oldState);         displayMessage(msg);     }      String convertStateToString(int state) {         if (state == Frame.NORMAL) {             return "NORMAL";         }         String strState = " ";         if ((state & Frame.ICONIFIED) != 0) {             strState += "ICONIFIED";         }         //MAXIMIZED_BOTH is a chain of 2 bits, and so         //we demand to examination for an exact lucifer.         if ((state & Frame.MAXIMIZED_BOTH) == Frame.MAXIMIZED_BOTH) {             strState += "MAXIMIZED_BOTH";         } else {             if ((land & Frame.MAXIMIZED_VERT) != 0) {                 strState += "MAXIMIZED_VERT";             }             if ((state & Frame.MAXIMIZED_HORIZ) != 0) {                 strState += "MAXIMIZED_HORIZ";             }             if (" ".equals(strState)){                 strState = "UNKNOWN";             }         }         return strState.trim();     } }              

    The Window Listener API

    The window listener API consists of iii window listener interfaces and the WindowEvent class. Their methods are listed in the following tables:
    • The WindowListener Interface
    • The WindowFocusListener Interface
    • The WindowStateListener Interface
    • The WindowEvent Grade
    The methods from all 3 interfaces are available through the WindowAdapter class.

    The WindowListener Interface

    Method Purpose
    windowOpened(WindowEvent) Called only after the listened-to window has been shown for the first time.
    windowClosing(WindowEvent) Called in response to a user request for the listened-to window to exist closed. To really close the window, the listener should invoke the window'due south dispose or setVisible(imitation) method.
    windowClosed(WindowEvent) Called simply later on the listened-to window has closed.
    windowIconified(WindowEvent)
    windowDeiconified(WindowEvent)
    Called just after the listened-to window is iconified or deiconified, respectively.
    windowActivated(WindowEvent)
    windowDeactivated(WindowEvent)
    Chosen just after the listened-to window is activated or deactivated, respectively. These methods are not sent to windows that are not frames or dialogs. For this reason, the windowGainedFocus and windowLostFocus methods to determine when a window gains or loses the focus are preferred.

    The WindowFocusListener Interface

    Method Purpose
    windowGainedFocus(WindowEvent)
    windowLostFocus(WindowEvent)
    Chosen just after the listened-to window gains or loses the focus, respectively.

    The WindowStateListener Interface

    Method Purpose
    windowStateChanged(WindowEvent) Called simply after the listened-to window'southward state is changed by being iconified, deiconified, maximized, or returned to normal. The state is available through the WindowEvent equally a bitwise mask. The possible values, divers in java.awt.Frame, are:
    • NORMAL. Indicates that no land $.25 are ready.
    • ICONIFIED.
    • MAXIMIZED_HORIZ.
    • MAXIMIZED_VERT.
    • MAXIMIZED_BOTH. Concatenates MAXIMIZED_HORIZ and MAXIMIZED_VERT. A window managing director may support MAXIMIZED_BOTH, while not supporting MAXIMIZED_HORIZ or MAXIMIZED_VERT. The java.awt.Toolkit method isFrameStateSupported(int) can be used to determine what states are supported by the window manager.

    The WindowEvent Class

    Method Purpose
    Window getWindow() Returns the window that fired the event. You can apply this instead of the getSource method.
    Window getOppositeWindow() Returns the other window involved in this focus or activation change. For a WINDOW_ACTIVATED or WINDOW_GAINED_FOCUS result, this returns the window that lost activation or the focus. For a WINDOW_DEACTIVATED or WINDOW_LOST_FOCUS event, this returns the window that gained activation or the focus. For any other blazon of WindowEvent with a Java awarding in a unlike VM or context, or with no other window, cypher is returned.
    int getOldState()
    int getNewState()
    For WINDOW_STATE_CHANGED events, these methods return the previous or new state of the window as a bitwise mask.

    Examples that Utilize Window Listeners

    The following table lists the examples that use window listeners.
    Instance Where Described Notes
    WindowEventDemo This department Reports all window events that occur on one window to demonstrate the circumstances nether which window events are fired.
    SliderDemo How to Use Sliders Listens for window iconify and deiconify events, then that it can stop the animation when the window isn't visible.
    InternalFrameEventDemo How to Write an Internal Frame Listener Reports all internal frame events that occur on one internal frame to demonstrate the circumstances under which internal frame events are fired. Internal frame events are like to window events.
    DialogDemo Text Component Features CustomDialog.java uses setDefaultCloseOperation instead of a window listener to determine what activity to accept when the user closes the window.
    Framework A demo that allows multiple windows to be created and destroyed.

adamshicientich.blogspot.com

Source: https://docs.oracle.com/javase/tutorial/uiswing/events/windowlistener.html

0 Response to "Java Open a Dialog Again Until Condition Is Met"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel