windowlistener.html
来自「jsf、swing的官方指南」· HTML 代码 · 共 978 行 · 第 1/3 页
HTML
978 行
<a href=../index.html target=_top>Creating a GUI with JFC/Swing</a> > <a href=index.html target=_top>Writing Event Listeners</a> </span> <div class=NavBit> <a target=_top href=undoableeditlistener.html>« Previous</a> • <a target=_top href=../TOC.html>Trail</a> • <a target=_top href=api.html>Next »</a> </div> <div id=PageTitle>How to Write Window Listeners</div> <blockquote>This section explains how to implement three kindsof window-related event handlers:<code>WindowListener</code>, <code>WindowFocusListener</code>,and <code>WindowStateListener</code>. All three handle<code>WindowEvent</code>s. The methods in allthree event handlers are implemented bythe abstract <code>WindowAdapter</code> class.<p>When the appropriate listener has been registeredon a window (such as a <a class="TutorialLink" target="_top" href="../components/frame.html">frame</a> or<a class="TutorialLink" target="_top" href="../components/dialog.html">dialog</a>), window events are fired just after the window isopened, closed, iconified, deiconified, activated, deactivated, maximized, restored to normal, or gains or loses the focus.<em>Opening</em> a window meansshowing it for the first time;<em>closing</em> it means removing the window from the screen.<em>Iconifying</em> it means substitutinga small icon on the desktop for the window;<em>deiconifying</em> means the opposite.A window is <em>activated</em> if it is a frame or a dialog that eitheris the focused window, or owns the focused window;<em>deactivation</em> is the opposite.<em>Maximizing</em> the window means increasing itssize to the maximum allowable, either in the verticaldirection, the horizontal direction, or both.<p><p>The <code>WindowListener</code> interface defines methods to handle most window events, such as the events for opening andclosing the window, activation and deactivation ofthe window, and iconification and deiconification ofthe window.<p>The other two window listener interfaces,<code>WindowFocusListener</code> and<code>WindowStateListener</code>, were introducedin release 1.4. <code>WindowFocusListener</code>contains methods to detect when the window has gainedor lost the focus. <code>WindowStateListener</code>has a single method to detect a change to the state of the window,such as when the window is iconified, deiconified,maximized, or restored to normal.<p><blockquote><hr><strong>Version note:</strong> Prior to release 1.4, focus-gained and focus-lostevents were inferred by using the <code>WindowListener</code>methods <code>windowActivated</code> and <code>windowDeactivated</code>. This approachdid not work with windows that were not frames or dialogs, because such windows never received those events.To determine a window's iconification, the<code>ComponentListener</code> methods <code>componentHidden</code>and <code>componentShown</code> were used. As of release 1.4,the methods defined in <code>WindowFocusListener</code>and <code>WindowStateListener</code> are preferred.<hr></blockquote><p>While you can use the <code>WindowListener</code>methods to detect some window state, such as iconification,there are a couple reasons why a <code>WindowStateListener</code>might be preferable: it has only one method for you to implement,and it provides support for maximization.<p><blockquote><hr><strong>Note:</strong> Not all window managers support all window states.The 1.4 <code>java.awt.Toolkit</code> method <a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/awt/Toolkit.html#isFrameStateSupported(int)"><code>isFrameStateSupported(int)</code></a> can be used to determine whether a particular windowstate is supported by a particular window manager.The WindowEventDemo example, describedlater in this section, shows how this method can be used.<hr></blockquote><p>A common use of window listeners isimplementing custom window-closing behavior.For example, you might use a window listenerto save data before closing the window,or to exit the program when the last window closes.<p>You don't necessarily need to implement a window listenerto specify what a window should do when the user closes it.By default, when the user closes a window the windowbecomes invisible.You can specify different behavior —disposing of the window, for example —using the <code>JFrame</code> or <code>JDialog</code><code>setDefaultCloseOperation</code> method.If you decide to implement a window-closing handler,then you might want to use<code>setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE)</code>to specify that your window listenertakes care of all window-closing duties. See<a class="TutorialLink" target="_top" href="../components/frame.html#windowevents">Responding to Window-Closing Events</a> for details on how to use <code>setDefaultCloseOperation</code>.<blockquote><hr><strong>Version note:</strong> As of release 1.4, when the last displayable windowwithin the Java virtual machine (VM) is disposed of,the VM may terminate. In previous releases, such as1.3, the VM remained running even if all windowswere disposed of. Note, however, that there can bea delay before the program exits automatically,and that under some circumstances the program mightkeep running. It is quicker and safer to explicitlyexit the program using <code>System.exit(int)</code>. See<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/awt/doc-files/AWTThreadIssues.html">AWT Threading Issues</a> for more information.<hr></blockquote><p>Another common use of window listenersis to stop threads and release resourceswhen a window is iconified,and to start up again when the window is deiconified.This way, you can avoid unnecessarilyusing the processor or other resources.For example,when a window that contains animation is iconified,it should stop its animation threadand free any large buffers.When the window is deiconified,it can start the thread againand recreate the buffers.<p>The following example demonstrates window events.A non-editable text area reports all window eventsthat are fired by its window.This demo implements all methods in the <code>WindowListener</code>,<code>WindowFocusListener</code>, and <code>WindowStateListener</code>interfaces. You can find the demo's code in <a class="SourceLink" target="_blank" href="examples/WindowEventDemo.java"><code>WindowEventDemo.java</code></a>.<p><h4 align=center><font color=red>[PENDING: screenshot forthcoming]</font></h4><blockquote><hr><strong>Try this:</strong> <ol><li> <a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/events/examples/WindowEventDemo.jnlp">Run WindowEventDemo</a> using <a href=http://java.sun.com/products/javawebstart> Java<sup><font size=-2>TM</font></sup> Web Start</a>. Or, to compile and run the example yourself, consult the <a href="examples/index.html#WindowEventDemo">example index</a>.<li> When the window appears, several messages are already displayed. One line reports whether your window manager supports MAXIMIZED_BOTH. If your window manager does not support other window states, this is also 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 also sent to standard output.<li> Click another window. You'll see "window lost focus" and "window deactivated" messages. If this window were not a frame or a dialog, it wouldn't receive the activated or deactivated events.<li> Click the WindowEventDemo window. You'll see "window activated" and "window gained focus" messages.<li> Iconify the window, using the window controls. Two iconification messages are displayed, one from the window listener and the other from the window state listener, though you won't see them until you deiconify the window, unless you are looking at standard output. Window-deactivation and window-lost-focus events are also reported.<li> Deiconify the window. Two deiconification messages are displayed, one from the window listener and the other from the window state listener. The <code>windowStateChanged</code> method in <code>WindowStateListener</code> gives the same information that you get using the <code>windowIconified</code> and <code>windowDeiconified</code> methods in <code>WindowListener</code>. Window-activation and window-gained-focus events are also reported.<li> Maximize the window, if your look and feel provides a way to do this. Note that some look and feels running on some window managers, such as 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 by resizing the window, but it is not a true maximization event. Some look and feels provide a way to maximize the window in the vertical or horizontal direction <em>only</em>. Experiment with your window controls to see what options are available.<li> Close the window, using the window controls. A window closing message is displayed. Once the window has closed, a window closed message is sent to standard output.</ol><hr></blockquote><p>Here is the demo's window event handling code:<blockquote><pre>public class WindowEventDemo ... implements WindowListener, WindowFocusListener, WindowStateListener { static JFrame frame; JTextArea display; public WindowEventDemo() { ... frame.addWindowListener(this); frame.addWindowFocusListener(this); frame.addWindowStateListener(this); checkWM(); } //Some window managers don't support all window states. //For example, dtwm doesn't support true maximization, //but mimics it by resizing the window to be the size //of the screen. In this case the window does not fire //the MAXIMIZED_ constants on the window's state listener. //Microsoft Windows supports MAXIMIZED_BOTH, but not //MAXIMIZED_VERT or MAXIMIZED_HORIZ. public void checkWM() { Toolkit tk = frame.getToolkit(); if (!(tk.isFrameStateSupported(Frame.ICONIFIED))) { displayMessage( "Your window manager doesn't support ICONIFIED."); } if (!(tk.isFrameStateSupported(Frame.MAXIMIZED_VERT))) { displayMessage( "Your window manager doesn't support MAXIMIZED_VERT."); } if (!(tk.isFrameStateSupported(Frame.MAXIMIZED_HORIZ))) { displayMessage( "Your window manager doesn't support 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 e) { displayMessage("WindowListener method called: windowClosing."); //A pause so user can see the message before //the window actually closes. ActionListener task = new ActionListener() { boolean alreadyDisposed = false; public void actionPerformed(ActionEvent e) { if (!alreadyDisposed) { alreadyDisposed = true; frame.dispose(); } else { //make sure the program exits System.exit(0); } } }; Timer timer = new Timer(500, task); //fire every half second timer.setInitialDelay(2000); //first delay 2 seconds 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 called: windowIconified."); } public void windowDeiconified(WindowEvent e) { 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 e) { displayStateMessage( "WindowStateListener method called: windowStateChanged.", e); } void displayMessage(String msg) { display.append(msg + newline); System.out.println(msg); } void displayStateMessage(String prefix, WindowEvent e) { int state = e.getNewState(); int oldState = e.getOldState(); String msg = prefix + newline + space + "New state: " + convertStateToString(state) + newline + space + "Old state: " + convertStateToString(oldState); display.append(msg + newline);
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?