Java Reference
In-Depth Information
•
HierarchyBoundsListener
: To find out when the frame moves or is resized. This works
similarly to
ComponentListener
, since the frame is the top-level container of component.
•
HierarchyListener
: To find out when the frame is shown or hidden.
•
InputMethodListener
: To work with input methods for internationalization.
•
KeyListener
: Normally not added to a
JFrame
. Instead, you register a keyboard action for
its content pane, like this:
JPanel content = (JPanel)frame.getContentPane();
KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
content.registerKeyboardAction(actionListener, stroke,
JComponent.WHEN_IN_FOCUSED_WINDOW);
•
MouseListener
and
MouseMotionListener
: To listen for mouse and mouse motion events.
•
PropertyChangeListener
: To listen for changes to bound properties.
•
WindowListener
: To find out when a window is iconified or deiconified or a user is trying
to open or close the window.
With the help of the
defaultCloseOperation
property, you typically don't need to add a
WindowListener
to help with closing the frame or stopping the application.
Extending JFrame
If you need to extend
JFrame
, this class has two important
protected
methods:
protected void frameInit()
protected JRootPane createRootPane()
By overriding either of these methods in a subclass, you can customize the initial appear-
ance and behavior of the frame or that of its
JRootPane
. For example, in the
ExitableJFrame
class shown in Listing 8-3, the default close operation is initialized to the
EXIT_ON_CLOSE
state.
Instead of calling
setDefaultCloseOperation()
for every frame created, you can use this class
instead. Because
JFrame
was subclassed, you don't need to add a call to the
frameInit()
method in either of the constructors. The parent class automatically calls the method.
Listing 8-3.
Closing Frames by Default
import javax.swing.JFrame;
public class ExitableJFrame extends JFrame {
public ExitableJFrame () {
}
public ExitableJFrame (String title) {
super (title);
}