Java Tutorial/Swing Event/Window Event — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Версия 17:44, 31 мая 2010
Содержание
- 1 extends WindowAdapter
- 2 Handle a window closing event
- 3 int java.awt.event.WindowEvent.WINDOW_OPENED
- 4 Listens for window iconify and deiconify events, so that it can stop the animation when the window isn"t visible.
- 5 Making a Window Handle its Own Events
- 6 Setting the Initial Focused Component in a Window
- 7 The event IDs for the WindowEvent class
- 8 The WindowListener Interface: events reflecting changes in the state of a window
- 9 Using Adapter Classes
- 10 Using WindowListener
- 11 WindowListener, WindowFocusListener, WindowStateListener
extends WindowAdapter
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Sun Microsystems nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
/* Framework.java requires no other files. */
public class Framework extends WindowAdapter {
public int numWindows = 0;
private Point lastLocation = null;
private int maxX = 500;
private int maxY = 500;
public Framework() {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
maxX = screenSize.width - 50;
maxY = screenSize.height - 50;
makeNewWindow();
}
public void makeNewWindow() {
JFrame frame = new MyFrame(this);
numWindows++;
System.out.println("Number of windows: " + numWindows);
if (lastLocation != null) {
// Move the window over and down 40 pixels.
lastLocation.translate(40, 40);
if ((lastLocation.x > maxX) || (lastLocation.y > maxY)) {
lastLocation.setLocation(0, 0);
}
frame.setLocation(lastLocation);
} else {
lastLocation = frame.getLocation();
}
System.out.println("Frame location: " + lastLocation);
frame.setVisible(true);
}
// This method must be evoked from the event-dispatching thread.
public void quit(JFrame frame) {
if (quitConfirmed(frame)) {
System.out.println("Quitting.");
System.exit(0);
}
System.out.println("Quit operation not confirmed; staying alive.");
}
private boolean quitConfirmed(JFrame frame) {
String s1 = "Quit";
String s2 = "Cancel";
Object[] options = { s1, s2 };
int n = JOptionPane.showOptionDialog(frame,
"Windows are still open.\nDo you really want to quit?",
"Quit Confirmation", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, options, s1);
if (n == JOptionPane.YES_OPTION) {
return true;
} else {
return false;
}
}
public void windowClosed(WindowEvent e) {
numWindows--;
System.out.println("Number of windows = " + numWindows);
if (numWindows <= 0) {
System.out.println("All windows gone. Bye bye!");
System.exit(0);
}
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
Framework framework = new Framework();
}
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application"s GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
class MyFrame extends JFrame {
protected Dimension defaultSize = new Dimension(200, 200);
protected Framework framework = null;
public MyFrame(Framework controller) {
super("New Frame");
framework = controller;
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
addWindowListener(framework);
JMenu menu = new JMenu("Window");
menu.setMnemonic(KeyEvent.VK_W);
JMenuItem item = null;
// close
item = new JMenuItem("Close");
item.setMnemonic(KeyEvent.VK_C);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Close window");
MyFrame.this.setVisible(false);
MyFrame.this.dispose();
}
});
menu.add(item);
// new
item = new JMenuItem("New");
item.setMnemonic(KeyEvent.VK_N);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("New window");
framework.makeNewWindow();
}
});
menu.add(item);
// quit
item = new JMenuItem("Quit");
item.setMnemonic(KeyEvent.VK_Q);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Quit request");
framework.quit(MyFrame.this);
}
});
menu.add(item);
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
setJMenuBar(menuBar);
setSize(defaultSize);
}
}
}
Handle a window closing event
import java.awt.Button;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
public class Main extends JFrame {
public static void main(String[] args) {
Main frame = new Main();
frame.setSize(new Dimension(200, 200));
frame.add(new Button("Hello World"));
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setVisible(true);
}
}
int java.awt.event.WindowEvent.WINDOW_OPENED
import java.awt.AWTEvent;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.ActionEvent;
import java.awt.event.ruponentEvent;
import java.awt.event.WindowEvent;
import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
public class Main implements AWTEventListener {
public void eventDispatched(AWTEvent evt) {
if (evt.getID() == WindowEvent.WINDOW_OPENED) {
ComponentEvent cev = (ComponentEvent) evt;
if (cev.getComponent() instanceof JFrame) {
System.out.println("event: " + evt);
JFrame frame = (JFrame) cev.getComponent();
loadSettings(frame);
}
}
}
public static void loadSettings(JFrame frame) {
System.out.println("loading");
}
public static void saveSettings() {
System.out.println("saving");
}
public static void main(String[] args) throws Exception {
Toolkit tk = Toolkit.getDefaultToolkit();
final Main main = new Main();
tk.addAWTEventListener(main, AWTEvent.WINDOW_EVENT_MASK);
final JFrame frame = new JFrame("");
frame.setName("your frame");
JMenuBar mb = new JMenuBar();
JMenu menu = new JMenu("File");
menu.add(new AbstractAction("Quit") {
public void actionPerformed(ActionEvent evt) {
try {
main.saveSettings();
System.exit(0);
} catch (Exception ex) {
System.out.println(ex);
}
}
});
mb.add(menu);
frame.setJMenuBar(mb);
frame.pack();
frame.setVisible(true);
}
}
Listens for window iconify and deiconify events, so that it can stop the animation when the window isn"t visible.
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
public class UsingWindowListener {
public static void main(String[] args) {
JFrame aWindow = new JFrame("This is the Window Title");
aWindow.setBounds(50, 100, 300, 300);
aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
aWindow.addWindowListener(new WindowListener() {
public void windowIconified(WindowEvent e) {
System.out.println(e);
}
public void windowDeiconified(WindowEvent e) {
}
public void windowOpened(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
}
public void windowClosed(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
});
aWindow.setVisible(true);
}
}
Making a Window Handle its Own Events
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
public class FrameHandlingEvents extends JFrame {
public FrameHandlingEvents(String title) {
setTitle(title);
// setDefaultCloseOperation(EXIT_ON_CLOSE);
enableEvents(java.awt.AWTEvent.WINDOW_EVENT_MASK);
}
protected void processWindowEvent(WindowEvent e) {
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
System.out.println(WindowEvent.WINDOW_CLOSING);
dispose();
System.exit(0);
}
super.processWindowEvent(e); // Pass on the event
}
public static void main(String[] a) {
FrameHandlingEvents window = new FrameHandlingEvents("Sketcher");
window.setBounds(30, 30, 300, 300);
window.setVisible(true);
}
}
Setting the Initial Focused Component in a Window
import java.awt.ruponent;
import java.awt.FlowLayout;
import java.awt.Window;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Main {
public static void main(String[] argv) throws Exception {
JFrame frame = new JFrame();
JButton component1 = new JButton("1");
JButton component2 = new JButton("2");
JButton component3 = new JButton("3");
frame.setLayout(new FlowLayout());
frame.add(component1);
frame.add(component2);
frame.add(component3);
InitialFocusSetter.setInitialFocus(frame, component2);
frame.pack();
frame.setVisible(true);
}
}
class InitialFocusSetter {
public static void setInitialFocus(Window w, Component c) {
w.addWindowListener(new FocusSetter(c));
}
}
class FocusSetter extends WindowAdapter {
Component initComp;
FocusSetter(Component c) {
initComp = c;
}
public void windowOpened(WindowEvent e) {
initComp.requestFocus();
e.getWindow().removeWindowListener(this);
}
}
The event IDs for the WindowEvent class
Event IDDescriptionWINDOW_OPENEDoccurs the first time a window is made visible.WINDOW_CLOSINGoccurs as a result of the close icon being selected or Close being selected from the window"s system menu.WINDOW_CLOSEDoccurs when the window has been closed.WINDOW_ACTIVATEDoccurs when the window is activated - obtains the focus, in other words. When another GUI component has the focus, you could make the window obtain the focus by clicking on it, for example.WINDOW_DEACTIVATEDoccurs when the window is deactivated - loses the focus, in other words. Clicking on another window would cause this event, for example.WINDOW_GAINED_FOCUSoccurs when the window gains the focus. This implies that the window or one of its components will receive keyboard events.WINDOW_LOST_FOCUSoccurs when the window loses the focus. This implies that keyboard events will not be delivered to the window or any of its components.WINDOW_ICONIFIEDoccurs when the window is minimized and reduced to an icon.WINDOW_DEICONIFIEDoccurs when the window is restored from an icon.WINDOW_STATE_CHANGEDoccurs when the window state changes - when it is maximized or minimized, for instance.
The WindowListener Interface: events reflecting changes in the state of a window
Defined MethodsDescriptionwindowOpened(WindowEvent e)Called the first time the window is openedwindowClosing(WindowEvent e)Called when the system menu Close item or the window close icon is selectedwindowClosed(WindowEvent e)Called when the window has been closedwindowActivated(WindowEvent e)Called when the window is activated - by clicking on it, for examplewindowDeactivated(WindowEvent e)Called when a window is deactivated - by clicking on another window, for examplewindowIconified(WindowEvent e)Called when a window is minimized and reduced to an iconwindowDeiconified(WindowEvent e)Called when a window is restored from an icon
Using Adapter Classes
An adapter class is a term for a class that implements a listener interface with methods that have no content (Ivor Horton"s Beginning Java 2, JDK 5 Edition by Ivor Horton Wrox Press 2005)
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
public class Sketcher {
JFrame window = new JFrame("Sketcher");
public Sketcher() {
window.setBounds(30, 30, 300, 300);
window.addWindowListener(new WindowHandler());
window.setVisible(true);
}
class WindowHandler extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.out.println("closing");
window.dispose(); // Release the window resources
System.exit(0); // End the application
}
}
public static void main(String[] args) {
new Sketcher();
}
}
Using WindowListener
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
public class Sketcher implements WindowListener {
static JFrame window = new JFrame("Sketcher");
public Sketcher() {
window.setBounds(30, 30, 300, 300);
window.addWindowListener(this);
window.setVisible(true);
}
public static void main(String[] args) {
new Sketcher();
}
public void windowClosing(WindowEvent e) {
System.out.println("closing");
window.dispose();
System.exit(0);
}
public void windowOpened(WindowEvent e) {
}
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) {
}
}
WindowListener, WindowFocusListener, WindowStateListener
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Sun Microsystems nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* WindowEventDemo
*/
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import java.awt.event.WindowListener;
import java.awt.event.WindowStateListener;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class WindowEventDemo extends JFrame implements WindowListener,
WindowFocusListener, WindowStateListener {
static final String newline = System.getProperty("line.separator");
static final String space = " ";
static WindowEventDemo frame = new WindowEventDemo("WindowEventDemo");
JTextArea display;
public static void main(String[] args) {
/* Use an appropriate Look and Feel */
try {
// UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
// UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
/* Turn off metal"s use of bold fonts */
UIManager.put("swing.boldMetal", Boolean.FALSE);
// Schedule a job for the event dispatch thread:
// creating and showing this application"s GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
// Create and set up the window.
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
// Set up the content pane.
frame.addComponentsToPane();
// Display the window.
frame.pack();
frame.setVisible(true);
}
private void addComponentsToPane() {
display = new JTextArea();
display.setEditable(false);
JScrollPane scrollPane = new JScrollPane(display);
scrollPane.setPreferredSize(new Dimension(500, 450));
getContentPane().add(scrollPane, BorderLayout.CENTER);
addWindowListener(this);
addWindowFocusListener(this);
addWindowStateListener(this);
checkWM();
}
public WindowEventDemo(String 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 manager 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 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 (frame.isDisplayable()) {
alreadyDisposed = true;
frame.dispose();
}
}
};
Timer timer = new Timer(500, task); // fire every half second
timer.setInitialDelay(2000); // first 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 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);
}
private void displayMessage(String msg) {
display.append(msg + newline);
System.out.println(msg);
}
private 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);
displayMessage(msg);
}
private String convertStateToString(int state) {
if (state == Frame.NORMAL) {
return "NORMAL";
}
String strState = " ";
if ((state & Frame.ICONIFIED) != 0) {
strState += "ICONIFIED";
}
// MAXIMIZED_BOTH is a concatenation of two bits, so
// we need to test for an exact match.
if ((state & Frame.MAXIMIZED_BOTH) == Frame.MAXIMIZED_BOTH) {
strState += "MAXIMIZED_BOTH";
} else {
if ((state & Frame.MAXIMIZED_VERT) != 0) {
strState += "MAXIMIZED_VERT";
}
if ((state & Frame.MAXIMIZED_HORIZ) != 0) {
strState += "MAXIMIZED_HORIZ";
}
}
if (" ".equals(strState)) {
strState = "UNKNOWN";
}
return strState.trim();
}
}