CATEGORII DOCUMENTE |
Asp | Autocad | C | Dot net | Excel | Fox pro | Html | Java |
Linux | Mathcad | Photoshop | Php | Sql | Visual studio | Windows | Xml |
DOCUMENTE SIMILARE |
||
|
||
One of the challenges of designing Java was to make a programming system that was compatible across different operating systems. Making a system that is also compatible across the various windowing platforms complicates this problem quite a bit. One of Java's greatest strengths is the architecture of its windowing classes, which successfully achieve the goal of cross-platform compatibility between windowing systems.
Java has been ported into several windowed operating systems: Microsoft Windows 95 and Window NT, Solaris with X-Windows/Motif, and Macintosh System 7. While these systems are all based on similar concepts of how a windowing system should look and behave, each has different underlying architecture and implementation details. Java cuts through the confusion among the various systems, providing a consistent presentation for all of them.
No matter which windowing system a Java application is actually running on, the system is accessed through the same generic set of Java classes. These classes have been abstracted so that they will work on any of the supported windowing systems. This abstraction layer, which sits between Java applications and the windowed operating system, is called the Abstract Windows Toolkit, or AWT for short. Figure 3-1 shows how the AWT classes present a consistent set of API methods to Java applications and applets regardless of what operating system is actually running the application.
Figure 3-1 The Abstract Windows Toolkit represents the
windowed operating system to Java applications
The AWT is described in detail in this chapter. The window hierarchy, upon which is based both Event notification routing and on-screen positioning of Containers and Components, is detailed. This chapter also covers how Events are delivered to Components and Containers by the Toolkit, as well as how on-screen repainting operations are scheduled and carried out. The other services provided by the Toolkit are also discussed.
The project for this chapter, FontLab, is an example of a Java application that utilizes the system-wide services of the Toolkit to catalogue the Fonts available on a particular system. FontLab also demonstrates how Component z-ordering, or overlaying of sibling Components on top of one another, is done in Java.
No matter what operating system you are using, the basic unit of a windowed user interface is, of course, the window. What is a generic window? Some basic attributes are obvious. First, a window occupies a rectangular area of the desktop surface. Second, a window's rectangle can be moved and resized to change its position and appearance on the desktop. Third, a window can be embedded within a parent window. In fact, all top-level windows can be said to be children of the desktop, which is just another large window. In Java, these three attributes have been abstracted to the Component class, which is discussed in Chapter 2.
An application's window can be thought of as the device the application uses to gather input from the user, just like any other I/O device. One of the most important and basic services a windowed operating system provides is a way to gather information about a user's actions. That is, if the user clicks the mouse on a window, it is the job of the windowed operating system to provide that input to the window's application. Only after the application has received a report of the user's actions can it react. Figure 3-2 shows how, among other I/O devices, an application's window is used to gather user interactions.
Figure 3-2 An application's window used to gather user
interactions
In Java, user interactions are called events. An Event is an object that contains information about a single action. One of the most important tasks of the Java AWT is to deliver Events to your Java application or applet windows.
The Component class has one public method to receive Events: postEvent. Again, Chapter 2 is dedicated to disussing the Component class in detail, so the particulars of the postEvent method are discussed there. In that chapter is a description of what happens to the Events after they have been delivered to a Component object. The question is, How do Events get delivered to Components in the first place?
It is the job of the AWT to translate user interactions within the windowed operating system into deliverable Events within Java. To accomplish this, the AWT uses a proxy architecture. Each Component object in a Java application is mirrored by an object in the windowed operating system. This object is a native item in the windowed operating system, whether that be a window in MS Windows, or a widget in the X-Windows/Motif operating system. Within AWT, a ComponentPeer object acts as the go-between between the Java Component object and the native operating system object. When a user interaction is posted to the native operating system object, the AWT and the ComponentPeer translate that user action into an Event. That Event is then handed to the Component object through its postEvent method.
More specifically, the AWT manages a Thread dedicated to delivering Events to Components. Because of their source (the user) Events are always asynchronous in nature. Figure 3-3 is a screenshot of the System.out output of a very simple Java application, which intentionally throws an exception when it receives an Event. This application has a window that throws an ArrayIndexOutOfBounds Exception in its postEvent implementation. The output displayed in Figure 3-3 is a stack-trace of the uncaught Exception. Note that the name of the Thread in which the Exception was thrown is AWT-Callback-Win32. This illustrates the name of the AWT Thread responsible for delivering Events to windows. In this case, the underlying windowed operating system is Windows NT. Here is the code for the simple application, called Spike, which was used to generate the Exception.
Figure 3-3 Stack-trace of the Spike program
An Event object is designed to encapsulate any type of user interaction. Mouse events such as mouse movements and clicks, keyboard events like keypresses or keyreleases, and other interactions are each encodable in a single Event object.
An Event object exposes its member variables rather than forcing you to access the variable through member methods. Though the object-oriented programming rule-of-thumb is that member variables shouldn't be available for other objects to modify directly (i.e., without at least using member methods to modify the values), Event objects are simple enough to forgo this kind of strict access control. In addition, it cuts down on code size to say myEvent.id rather than myEvent.getID().
The id member variable indicates which type of Event has occurred. Here are the possible values for Event.id which are specific to Window objects, that is, the values that indicate events created by Java.
Event Type |
Description |
|
|
WINDOW_DESTROY |
The window has received a command to destroy itself. Only Window class objects will receive this type of Event. Call Window.dispose() to properly destroy the Window. |
WINDOW_EXPOSE |
The window has become exposed. |
WINDOW_ICONIFY |
The window has become iconified. |
WINDOW_DEICONIFY |
The iconic window has become de-iconified. |
WINDOW_MOVED |
The window has been moved (and possibly resized). |
|
There is nothing stopping an application from creating its own custom Event types and passing them to Component windows. The Component class description in Chapter 2 describes the keyboard and mouse Events which may be sent to a Component object. In Chapters 4 and 5 the Event IDs reserved for Scrollbar and List objects are discussed in detail.
As suggested earlier, a window can be thought of as an Input/Output device. AWT's architecture creates an efficient system for delivering Events to windows. Events are the Input end of a window. A window is also an output device. The output is what the window displays on the surface of its rectangle.
All of the windowing operating systems handle painting windows in a similar manner. The windowing system determines when a window must repaint itself based on window management. For example, if two windows are overlapping and the window on top is removed, then the windowing system flags that the remaining window must be repainted as soon as possible. (Actually, just the part of the remaining window which was uncovered is flagged for repainting.)
The repaint operation is an asynchronous operation for a couple of reasons. First, the system usually determines a window must be repainted as a side effect of some operation the system is trying to perform. In this case, the repainting operation must be scheduled for some time in the future. Second, repainting can be a time-intensive procedure. The system attempts to store as many redundant repainting operations for the same window as possible. When the system thinks there is enough idle time to repaint the window, then it will explicitly ask the window to repaint itself.
In the AWT, a window is requested to repaint its surface via Component.update(). Chapter 2 explained what happens within the Component class after the system calls update(), but what causes update() to be called in the first place? A similar callback mechanism to the Event delivery procedure described earlier is used. When the underlying windowing system issues a repaint command to the native window object associated with a Java Component, the AWT translates this to a call to the Component's update() method.
Figure 3-4 shows the Spike2 application. Like the previous Spike application, Spike2 throws an ArrayIndexOutOrBoundsException in the update() method of its main window. Figure 3-4 also includes a stack-trace at the time the exception is thrown. Notice the same Thread, AWT-Callback-Win32, controls the repainting operation as controlled by the Event delivery operation in Spike. Here is the code for the Spike2 application.
Figure 3-4 The Spike2 application
Of course, rather than throwing Exceptions during repainting or Event handling methods, your code should handle each call as quickly as possible. Stalling or suspending the callback Thread will adversely affect your application in unforeseen ways.
The Component class defines a child window. That means that a simple Component window must exist as a child to a parent window. The Component class is written so that a Component does not have its native windowing system peer created unless the Component has been added to a parent window. This is reflected in the Java API by the fact that you can't display a simple Component, such as a Canvas or Scrollbar, on the desktop without a parent window.
A special subclass of Component is the Container class. A Container window is a type of Component that can be a parent to other Components, including other Containers. To add a Component as the child of a Container, you use the Container class method add(), shown here:
Container cont;A Container contains zero or more Components. These Components are called siblings, since they have the same parent window. One important thing to remember is that sibling windows "clip" each other. That is, if you had two overlapping sibling windows, one of the windows appears on top of the other.
The term denoting the relative precedence of sibling Components is z-order. A Component with a higher z-order will appear on top of its overlapping siblings. The z-order of sibling Components is determined by the order in which they were added to the parent Container. The last Component added to a Container has the lowest z-order. Any Component added before another Component will appear on top if the two overlap within the parent Container.
Note that all Containers have a LayoutManager which arranges the child Components within the Container. The Java API includes several types of LayoutManagers to arrange child Components by different methods. For example, a FlowLayout object will arrange a Container's child Components side-by-side, left-to-right, top-to-bottom. Chapter 4 discusses the various LayoutManager classes.
Because the LayoutManager classes, included with the Java API, ensure that sibling Components never overlap within their parent Containers, our discussion of z-ordering is academic as long as you use only those LayoutManagers in your Containers. However, in Containers that do have overlapping child Components (as would be the case if you implemented your own LayoutManager to cause siblings to overlap, as is done in the chapter's project) z-ordering can be important.
You can also remove a Component from its Container. The remove method takes, as a reference, the Component you want removed as a child for the Container. When the Component is removed from its parent Container, the Component's native windowing system peer is automatically destroyed. Again, a Component can not have a native peer object unless the Component has a parent.
The following AddButton application demonstrates the use of Container.add() and Container.remove().The AddButton application includes a "+" and "-" push button. Press the "+" button to create a new button Component. Press the "-" button to destroy the oldest button Component. The other buttons do nothing. Figure 3-5 shows the AddButton application.
Figure 3-5 The AddButton application
As stated above, a Container is a special type of Component that can be a parent to zero or more child Components, including other Containers. A Container is still a Component, however, and, as such, the Container must also have a parent window.
The Window class is a subclass of Container that defines a top-level window. Top-level windows do not have to have parent windows. The native windowing system peer for a Window object is a pop-up window on the desktop. Therefore, when creating your user interface in Java, all Component objects must eventaully be descended from a Window object in the window hierarchy.
A Frame is a special type of Window. A Frame is a native windowing system top-level frame window, which has a titlebar, an optional menubar, and a resizable border. Note that in the sample applications in this chapter, the interface is always controlled by an object derived from Frame. That Frame is the application's main window.
How do the native windowing system objects, the peers, get created? Where do they come from? Earlier, we said that Component objects (execpt Window and Frame objects) do not have a peer created for them in the native windowing system until the Component is added as a child of a Container. Another way of putting it is: The Component does not have a peer created on its behalf until it is added to a Container that has a peer.
A Component's own addNotify method is called to create the Component's peer. Component.addNotify() is called by the parent Container. This call can happen either in Container.add(), as soon as the Component is added to the Container, or in Container.addNotify(). In the case of addNotify(), when a Container's peer is created, the Container also tells its child Components to create their peers.
Simple Component objects, such as a Canvas, create their own peers in overriden implementations of addNotify(). The Java code for Canvas.addNotify() looks something like this:
CanvasPeer _myPeer = null;Toolkit is the java.awt.Toolkit class.The Toolkit class is the class that represents the capabilities of the underlying windowing system to Java objects. For example, the createCanvasPeer method used above, uses native function calls to the underlying windowing system to create a CanvasPeer object. The CanvasPeer is a representative of a native windowing object in Java.
Within the Toolkit class is a create method for each of the Component types in the Java API. There is a Toolkit.createCanvasPeer, Toolkit.createButtonPeer, Toolkit.createScrollbarPeer, and so on, defined in the Toolkit class. The actual peer classes are discussed in detail in Chapter 9. The point being made here is that each Component class object uses the Toolkit to create its peer, and the creation of the peer occurs within the overriding implementation of addNotify. The Frame class calls its own addNotify method within Frame.show. That is, as soon as the Frame is supposed to be shown on the screen, its peer is created.
The Toolkit represents the windowing system within Java code. Most of the Toolkit's public methods are dedicated to the creation of peer components. The native windowing system provides additional functionalities beyond simply creating and managing windows. The Toolkit also exposes some of these additional functionalitites. The Toolkit class currently has methods to provide services in three additional areas: desktop metrics, available font information, and image downloading/preparation.
The size and composition of the desktop surface can be of great importance to some applications. Through the Toolkit's public methods, you can find out more about the desktop. The following table lists the Toolkit's desktop metrics methods and provides a description of each.
Method |
Description |
|
|
getScreenSize |
Returns a Dimension object whose width and height is equal to the width and height of the desktop, in pixels. |
getScreenResolution |
Returns resolution of the desktop, in pixels-per-inch. |
getColorModel |
Returns the ColorModel of the desktop. If the system uses a 256-color display, then this would be an IndexedColorModel, which would give you read access to the system palette. |
|
It is through the Toolkit that an application or applet can enumerate the fonts available on the system. Toolkit.getFontList() returns an array of Strings. Each element of the array is a typeface name for a font available on the system. To get the FontMetrics for a Font when it is used on the desktop screen, you can use getFontMetrics, passing in the Font that is to be measured. Note that FontMetrics are also available through Graphics.getFontMetrics.
The image methods included in the Toolkit, allow an application to download and display images. To create an Image object from a graphics-format file, use Toolkit.getImage(). Two overloaded versions of this method are provided. The first version takes a URL pointing to the network location of the graphics format file. The second version takes a file path name and loads the image from a file on the local file system.
The Image object returned from getImage represents the graphics format file to Java. Before the Image can be copied to a display surface, the Image must be fully "prepared," or constructed in memory. The Toolkit's prepareImage method is used to kick-start the Image construction process. prepareImage takes, as a parameter, an ImageObserver. The ImageObserver will be notified as to the progress of the Image construction process. Any errors in the graphics file will also be reported to the ImageObserver. After an Image has been fully prepared once, it can be drawn on any display surface any number of times. checkImage is used by objects, other than the ImageObserver, to get information on the progress of the Image construction process.
Chapter 1 on Applets and Graphics, discusses downloading and preparing images because image and audio data have such an important application over the Internet.
Table 3-1 lists the classes summarized in this chapter and a short description of each. Table 3-2 lists the methods of the classes from Table 3-1 and provides a short description of each method.
|
||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Container
Purpose
A Container is a Component which can contain other Components, including other Containers.
Syntax
public abstract class Container extends Component
Description
A Container is a Component that can contain other Components, including other Containers. A Container, being a Component, must be contained by another Container in order to be displayed. The Container class is abstract. The simplest type of realizable Container is a Panel. Figure 3-6 shows the class hierarchy of the Container class.
PackageName
java.awt
Imports
java.io.PrintStream, java.awt.peer.ContainerPeer
Constructors
None.
Parameters
None.
Figure 3-6 The class hierarchy of the Container class
countComponents
ClassName
Container
Purpose
Gets the number of child Components for this Container.
Syntax
public int countComponents();
Parameters
None.
Description
Returns the number of child Components in this Container.
Imports
None.
Returns
The number of Components that have been added to this Container using add.
See Also
The getComponent and getComponents methods of the Container class
Example
This example Container subclass demonstrates the use of both countComponents and getComponent to run through the list of a Container's child Components. The only method implemented by this class, getChildrenBounds returns a bounding rectangle of all the child Components.
class ContainerEx extends ContainergetComponent
ClassName
Container
Purpose
Gets a reference to a specific child Component of this Container.
Syntax
public Component getComponent(int index)
Parameters
index
Zero-based index of the Component to get. This must be between 0 and (countComponents()-1).
Description
Gets a reference to one of the child Components of this comtainer. An ArrayIndexOutOfBoundException may be thrown if the index parameter is not valid.
Imports
java.awt.Component
Returns
A reference to the index-th Component child of the Container will be returned. Note that if the index parameter is less than 0 or greater than (countComponents()-1), then an ArrayIndexOutOfBoundsException will be thrown.
See Also
The Component class; the countComponents and getComponents methods of the Container class
Example
See the example under countComponents.
getComponents
ClassName
Container
Purpose
Gets an array of references to all child Components of this Container.
Syntax
public Component[] getComponents();
Parameters
None.
Description
Gets an array of Component, with one element for each of the child Components of the Container. The order of the Components in the array is the order the Components were added to this Container.
Imports
java.awt.Component
Returns
An array of Component objects. The length of this array will be the same as the return value from countComponents. Each child Component will appear in the array. Null may be returned if the Container has no children.
See Also
The Component class; the countComponents and getComponent methods of the Container class
Example
This is an alternative implementation to the getChildrenBounds function given in the example for the countComponents method.
class ContainerEx extends Containerinsets
ClassName
Container
Purpose
Specifies inset spacing between children and the Container's edge.
Syntax
public Insets insets();
Parameters
None.
Description
A Container can define an Insets object, which defines the border of padding within the Container. The Insets are used by the LayoutManager in such a way that no child Components will be placed within the Insets border.
Imports
java.awt.Insets
Returns
An Insets object is returned that describes the border for a LayoutManager to leave around the Container.
See Also
The LayoutManager class; the Insets class
Example
The default implementation of Insets simply delegates the call to the Container's peer. If the peer does not define an Insets, then Insets of 0 are returned. This implementation of insets and setInsets allows you to define your Container's Insets within Java code.
public ContainerEx extends Containeradd
ClassName
Container
Purpose
Adds a Component as a child of this Container.
Syntax
public void add(Component c);public void add(Component c, int index);
Parameters
Component c
The Component to add as a child of this Container.
int index
Index to store the Component in the Container's internal list of Components.
Description
Adds a Component as a child of this Container. The index of the Component, within the Container's list of Components, is set by the second parameter, index, of the second overloaded versions. No matter which version you use, the child Component has the lower z-order compared to its siblings. If the Component is currently a child of another Container, it will automatically be removed from the other Container before being added to this one. If the Component is a parent or ancestor of this Container, then an IllegalArgumentException will be thrown.
Imports
java.awt.Component.
Returns
None.
See Also
The Component class; the remove method of the Container class
Example
This example builds a simple toolbar of four buttons.
.// A Panel is a type of Container.remove
ClassName
Container
Purpose
Removes a Component as a child of this Container.
Syntax
public void remove(Component c);
Parameters
Component c
A Component which is a child of this Container.
Description
Removes a Component as a child of this Container. If the Component is not a child of this Container, then the call is ignored. The Component is added as a child of this Container using add.
Imports
java.awt.Component
Returns
None.
See Also
The Component class; the add method of the Container class
Example
This example removes all child Components and then adds them back in reverse order.
public class MyCont extends PanelremoveAll
ClassName
Container
Purpose
Removes all child Components from this Container.
Syntax
public void removeAll();
Parameters
None.
Description
Removes all the child Components from this Container. Internally, this method is implemented by running through the list of Components and making repeated calls to remove.
Imports
None.
Returns
None.
See Also
The remove method of the Container class
Example
See the example under the remove method of the Container class.
getLayout
ClassName
Container
Purpose
Gets the LayoutManager for this Container.
Syntax
public LayoutManager getLayout();
Parameters
None.
Description
Gets the LayoutManager for this Container. The LayoutManager is responsible for arranging the child Components within the Container's display rectangle. See Chapter 4 for a description of the LayoutManager and its relationship with the Container.
Returns
A reference to the Container's LayoutManager. Null if the Container has no LayoutManager.
See Also
The LayoutManager interface; the setLayout method of the Container class
Example
This example uses getLayout to display a Container's LayoutManager.
public class displayLayout(Container cont)setLayout
ClassName
Container
Purpose
Sets the LayoutManager for this Container to use.
Syntax
public void setLayout(LayoutManager lm);
Parameters
LayoutManager lm
A LayoutManager to arrange the Components of this Container.
Description
Sets the LayoutManager which will arrange the child Components of this Container within the Container's bounding rectangle. See Chapter 4 for a description of the LayoutManager and its relationship with the Container.
Imports
java.awt.LayoutManager
Returns
None.
See Also
The LayoutManager interface; the getLayout method of the Container class
Example
This example Applet sets its own LayoutManager to a BorderLayout object.
public class MyApplet extends Appletlayout
ClassName
Container
Purpose
Called to allow the Container to arrange its child Components.
Syntax
public void layout();
Parameters
None.
Description
The default implementation of this method forces the LayoutManager to recalculate the placement of child Components within this Container's rectangle using the LayoutManager's layoutContainer method. The default implementation of the validate method of the Component class calls Component.layout. The Container class overrides layout with a custom implementation. See Chapter 4 for a description of the LayoutManager and its relationship with the Container.
Imports
None.
Returns
None.
See Also
The LayoutManager interface; the validate() method of the Component class
Example
In this example, a custom Container does not rely on a LayoutManager but instead arranges its child Components in an overridden layout implementation.
public class MyCont extends Panelvalidate
ClassName
Container
Purpose
Called when the Container should validate is size and positioning and that of its child Components.
Syntax
public void validate();
Parameters
None.
Description
This overridden version of Component.validate does everything the Component version of this method does, plus it will validate all the child Components of this Container. A Container is invalidated by an explicit call to Component.invalidate. A Container is also invalidated whenever a Component is added to it or removed from it.
Imports
None.
Returns
None.
Example
See the AddButton example given earlier in this chapter.
preferredSize
ClassName
Container
Purpose
Calculates the preferred size of this Container's bounding rectangle using the Container's LayoutManager.
Syntax
public Dimension preferredSize();
Parameter
None.
Description
This overridden implementation of Component.preferredSize calculates the Container's preferred size by asking the LayoutManager to calculate the preferred size in a call to LayoutManager.preferredLayoutSize. See Chapter 4 for a description of the LayoutManager and its relationship with the Container.
Imports
None.
Returns
A Dimension object whose width and height member variables hold the preferred size of this Container.
See Also
The preferredSize method of the Component class; the minimumSize method of the Container class
Example
See the example of the preferredSize method of the Component class (in Chapter 2).
minimumSize
ClassName
Container
Purpose
Calculates the minimum acceptable size of this Container's bounding rectangle using the Container's LayoutManager.
Syntax
public Dimension minimumSize();
Parameters
None.
Description
This overridden implementation of Component.minimumSize calculates the Container's minimum size by asking the LayoutManager to calculate the minimum size in a call to LayoutManager.minimumLayoutSize. See Chapter 4 for a description of the LayoutManager and its relationship with the Container.
Imports
None.
Returns
A Dimension object whose width and height member variables hold the preferred size of this Container.
See Also
The minimumSize method of the Component class; the preferredSize method of the Container class
Example
See the example for the minimumSize method of the Component class (in Chapter 2).
paintComponents
ClassName
Container
Purpose
Synchronously paints all children Components.
Syntax
public void paintComponents(Graphics g)
Parameters
Graphics g
The Graphics, associated with the display surface, to paint the Components on.
Description
Forces an immediate (synchronous) repainting of all the child Components. A synchronous repainting of each of the child Components is achieved by creating multiple clipped versions of the passed Graphics object (using Graphics.create), and passing the clipped versions to paint for each of the child Components to render itself.
Imports
java.awt.Graphics.
Returns
None.
See Also
The paint method of the Component class; the create method of the Graphics class
Example
In this example, Container's paint method is implemented by a simple call to paintComponents. This repaints the Container's child Components using the Graphics object passed to the Container's paint method.
public class MyContainer extends PaneldeliverEvent
ClassName
Container
Purpose
Delivers an Event to a Container or one of its child Compnents.
Syntax
public void deliverEvent(Event evt)
Parameters
Event evt
The Event to deliver to this Container.
Description
This overridden version of Component.deliverEvent first passes the Event to the child Component indicated by the x and y member variables of the Event object. If the child Component does not handle the event, or the x and y Event member variables do not indicate a point within any of this Container's children, then the Event is posted to this Container through Container.postEvent.
Imports
java.awt.Event.
Returns
None.
See Also
The deliverEvent method of the Component class
Example
In this example, mouse events are successfully delivered to "virtual" (peerless) child Components of a Container using the Container's deliver Event method. The deliverEvent method of the Container class first attempts to post the Event to an appropriate child Component before letting the Container handle the Event.
//First, here's our peerless Component classlocate
ClassName
Container
Purpose
Gets the child located at a particular point.
Syntax
Public Component locate(int x, int y);
Parameters
int x, y
Indicates a point relative to the Container's point of origin.
Description
Finds the Component which occupies the point, passed in the x and y parameters, to this method. The x and y parameters are expressed relative to this Container's origin.
Imports
java.awt.Component
Returns
The Component with lowest index in the Container's internal list of Components and which occupies a rectangle that the point falls into, is returned.
Example
This example lists the source code for the Container class' deliverEvent method. The deliverEvent method uses the locate method to find the correct child Component to deliver an Event to.
public void deliverEvent(Event evt) elseEvent
Purpose
Represents an asynchronous event which occurred in the system.
Syntax
public class Event
Description
Represents an asynchronous event which occurred in the system. For example, user-generated events like mouse moves or keyboard actions. The Event class is not extended by any class in the Java API, but rather the member variables of the Event class are sufficient for encoding any definable event. Figure 3-7 shows the class hierarchy of the Event class.
PackageName
java.awt
Imports
java.io.*
Constructors
public Event(Object target, long when, int id, int x, int y, int key, int modifiers, Object arg);public Event(Object target, long when, int id, int x, int y, int key, int modifiers);public Event(Object target, int id, Object arg);
Parameters
The following table lists all of the Event class public member variables and a short description of each.
Figure 3-7 The class hierarchy of the Event class
Member Variable |
Description |
|
|
Object target |
The Object to which the Event was originally passed. |
long when |
Time stamp of when the event occurred. |
id |
Identifies the type of the Event: mouse movement, keyboard action, etc. The following table lists all of the different Event types. |
int x, y |
A point where the Event occurred. These two variables are ususally only valid for mouse Events. |
int key |
The key pressed if this is a keyboard Event. |
modifiers |
Keyboard Event modifiers, such as whether or not the key was being held down, whether or not the key was being held down, etc. |
clickCount |
For multiclicks (e.g., a double-click) this member indicates how many clicks took place. |
Object arg |
An arbitrary argument, which is different for each type of Event. |
Event evt |
The next Event. Used when storing Events in a linked list. |
|
The id member variable indicates what type of Event is being represented. Many different Event class constants have been defined to indicate Event types. The following table list the possible values for the id field.
Event Type |
Description |
|
|
WINDOW_DESTROY |
This a command for the Window object to destroy itself. To destroy a Window, use Window.dispose(). |
WINDOW_ICONIFY |
The Window has been iconified. |
WINDOW_DEICONIFY |
The iconified Window has been restored. |
WINDOW_MOVED |
The Window has been moved on the desktop. |
KEY_PRESS |
The user has pressed a key. Examine key and modifiers members to see which key. |
KEY_RELEASE |
A pressed key has been released. Examine key and modifiers members to see which key. |
MOUSE_DOWN |
The mouse button has been clicked. Examine x and y members to see where the mouse click occurred. |
MOUSE_UP |
The mouse button has been released. Examine x and y members to see where the mouse click occurred. |
MOUSE_ENTER |
The mouse has entered the rectangle dedicated to this Component. Examine x and y members to see where the mouse click occurred. |
MOUSE_EXIT |
The mouse has left the rectangle dedicated to this Component. Examine x and y members to see where the mouse click occurred. |
MOUSE_DRAG |
Same as a MOUSE_MOVE, but with the mouse button held down. |
MOUSE_MOVE |
The mouse has been moved. Examine x and y members to see where the mouse cursor was moved to. |
SCROLL_LINE_UP |
The target member holds a reference to the Scrollbar which the user clicked. The arg member holds the value of the Scrollbar. |
SCROLL_LINE_DOWN |
The target member holds a reference to the Scrollbar which the user clicked. The arg member holds the value of the Scrollbar. |
SCOLL_PAGE_UP |
The target member holds a reference to the Scrollbar which the user clicked. The arg member holds the value of the Scrollbar. |
SCROLL_PAGE_DOWN |
The target member holds a reference to the Scrollbar which the user clicked. The arg member holds the value of the Scrollbar. |
SCROLL_ABSOLUTE |
The target member holds a reference to the Scrollbar which the user clicked. The arg member holds the value of the Scrollbar. This message is sent when the user holds down and drags the thumb of a Scrollbar. |
LIST_SELECT |
The target member holds a reference to the List which the user clicked. The arg member holds the value of the selected list item. |
LIST_DESELECTED |
The target member holds a reference to the List which the user clicked. The arg member holds the value of the selected list item. |
ACTION_EVENT |
When a Button is clicked, target is the Button, arg is the Button's text. When a menu item was selected, target is the selected menu item, arg is the Button's text. |
GET_FOCUS |
The Component in target has just received focus. |
LOST_FOCUS |
The Component in target has just lost focus. |
|
The modifiers member is a bitmap representing the state of special function keys during keyboard and mouse Events. The following table lists the recognized values which may be present in the modifiers member. These values are ORed together bitwise to form the values of the modifiers member.
Mask |
Description |
|
|
SHIFT_MASK |
Set if the key was held down. |
CTRL_MASK |
Set if the key was held down. |
META_MASK |
Set if the key was held down. |
ALT_MASK |
Set if the key was held down. |
|
translate
ClassName
Event
Purpose
Changes the x and y member variables of the Event by some value.
Syntax
public void translate(int dX, int dY);
Parameters
int dX, dY
The Event's x member variable is modified by adding dX to it, and the Event's y member variable is modified by adding dY to it.
Description
Similar to translate, this method modifies the Event's x and y member variables by adding a dX and a dY value to them. Internally, this method is called by Component.postEvent when the Event is passed on to the Component's Container in order to reflect the point in terms of the Container's origin.
Imports
None.
Returns
None.
Example
This Component's overridden mouseDown and mouseUp Event handlers change the location of mouse clicks and mouse releases by ten points in the X and Y directions before allowing the Events to be passed on to the Component's parent Container.
public class MyComponent extends CanvasshiftDown
ClassName
Event
Purpose
Tells whether or not the key was held down when the Event was created.
Syntax
public boolean shiftDown();
Parameters
None.
Description
Tells whether or not the SHIFT_MASK flag is set in the modifiers member variable. Using this member method is a little easier than testing the modifiers variable directly. The SHIFT, CTRL, and META masks are only valid for keyboard and mouse Events.
Returns
True is returned if the SHIFT_MASK flag is set in the modifiers member variable. Otherwise, false.
See Also
The controlDown and metaDown methods of the Event class
Example
This example mouseDown Event handler sends mouse Events to subhandlers according to the states of the SHIFT, CTRL, and META flags.
public class MyComponent extends CanvascontrolDown
ClassName
Event
Purpose
Tells whether or not the key was held down when the Event was created.
Syntax
public boolean controlDown();
Parameters
None.
Description
Tells whether or not the CTRL_MASK flag is set in the modifiers member variable. Using this member method is a little easier than testing the modifiers variable directly. The SHIFT, CTRL, and META masks are only valid for keyboard and mouse Events.
Returns
True is returned if the CTRL_MASK flag is set in the modifiers member variable; otherwise, false.
See Also
The shiftDown and metaDown methods of the Event class
Example
See the example under the shiftDown method of the Event class.
metaDown
ClassName
Event
Purpose
Tells whether or not the
Syntax
public boolean metaDown();
Parameters
None.
Description
Tells whether or not the META_MASK flag is set in the modifiers member variable. Using this member method is a little easier than testing the modifiers variable directly. The SHIFT, CTRL, and META masks are only valid for keyboard and mouse Events.
Returns
True is returned if the META_MASK flag is set in the modifiers member variable; otherwise, false.
See Also
The shiftDown and controlDown methods of the Event class
Example
See the example under the shiftDown method of the Event class.
Window
Purpose
The Window class is a top-level Container class.
Syntax
public class Window extends Container
Description
The Window class is a top-level Container class. Window class objects do not have parent Containers. Instead, Window objects can be thought of as children of the desktop. The Frame and Dialog classes are special types of Window classes. Figure 3-8 shows the class hierarchy of the Window class. Do not create a Window object directly, but instead use either the Frame class or the Dialog class to create top-level windows. The Window class implements the methods that are shared between the two specific classes.
PackageName
java.awt
Imports
java.awt.peer.WindowPeer
Constructors
public Window();
public Window(Frame parent);
The first constructor creates a top-level Frame window. The second constructor
creates a top-level window which is a child of the passed Frame, such as a
modeless Dialog.
Parameters
None.
Example
See the examples for the Frame and Dialog classes.
Figure 3-8 The class hierarchy of the Window class
toBack
ClassName
Window
Purpose
Sends the Window to the back of the desktop z-order..
Syntax
public void toBack();
Parameters
None.
Description
Sends the Window to the back of the desktop z-order. If the Window is not showing, this call is ignored. The Window automatically loses keyboard focus after this call is made if the window, or any of its children, have the keyboard focus when the call is made.
Imports
None.
Returns
None.
See Also
The toFront method of the Window class
Example
In this example, a custom Event is delivered to the MyWindow class to cause it to be sent to the back or the front of the z-order of the top-level windows.
public class MyWindow extends WindowtoFront
ClassName
Window
Purpose
Brings the Window to the front of the desktop z-order..
Syntax
public void toFront();
Parameters
None.
Description
Brings the Window to the front of the desktop z-order. If the Window is not showing, this call is ignored. The Window automatically gains keyboard focus after this call is made.
Imports
None.
Returns
None.
See Also
The toBack method of the Window class
Example
See the example for the toBack method of the Window class.
dispose
ClassName
Window
Purpose
Destroys the Window object's native windowing system peer.
Syntax
public void dispose();
Parameters
None.
Description
Destroys the Window's native windowing system peer object. Top-level windows must explicitly destroy (dispose) of their peers. Most commonly used when an application's main window receives a WINDOW_DESTROY Event.
Imports
None.
Returns
None.
Example
This example Event handler, for an application's main Frame window, calls dispose when it receives a WINDOW_DESTROY Event.
public class MyAppMainFrame extends FramegetWarningString
ClassName
Window
Purpose
Gets the Applet warning string to display in Frame windows created by Applets.
Syntax
public final String getWarningString();
Parameters
None.
Description
The warning string is a string that displays in a Frame window created by an Applet object. For example, the Netscape Navigator v2.0 displays a string "Untrusted Applet Window" on every Frame window created by Applets. Note that this method is final, so your Applet cannot override this implementation. The warning string is actually a System property called "awt.appletWarning".
Imports
None.
Returns
A String object containing the warning string to display.
Example
This custom Frame class uses the warning string as the Frame's caption.
public class MyFrame extends FrameToolkit
Purpose
The Toolkit class represents the native windowing system in Java.
Syntax
public abstract class Toolkit
Description
The Toolkit class represents the native windowing system in Java. The four functionalities accessible through the Toolkit class are: Component peer creation, Font enumeration and metrics, Screen sizing and resolution, and Image loading and preparation. Figure 3-9 shows the class hierarchy of the Toolkit class. The Toolkit class is an abstract class, so you cannot create an instance of this class. Instead, you use the Toolkit class' getDefaultToolkit method to obtain a reference to the Toolkit implementation in use on the system currently, as demonstrated in the example for the getDefaultToolkit method listed below.
PackageName
java.awt
Imports
java.awt.peer.*, java.awt.image.ImageObserver, java.awt.image.ImageProducer, java.awt.image.ColorModel, java.net.URL
Constructors
None.
Parameters
None.
Figure 3-9 The class hierarchy of the Toolkit class
getScreenSize
ClassName
Toolkit
Purpose
Gets the dimension of the desktop in pixels.
Syntax
public Dimension getScreenSize();
Parameters
None.
Description
Gets the dimension of the desktop in pixels. This is very useful for applications which would like to layout their Components based on available on-screen real estate.
Imports
java.awt.Dimension
Returns
The return Dimension object's width and height members reflect the width and height of the desktop.
See Also
The getScreenResolution method of the Toolkit class
Example
This example method centers a Frame on the desktop.
public void centerFrameOnDesktop(Frame f)getScreenResolution
ClassName
Toolkit
Purpose
Gets the resolution of the desktop.
Syntax
public int getScreenResolution();
Parameters
None.
Description
Gets the resolution of the desktop in pixels per inch. The number returned is valid in both the X and Y directions. This is useful for applications which need to know physical, not logical, distances on the desktop. For example, an application which is supposed to display a 12-inch ruler would need to know how many pixels from the upper-left corner of the screen is exactly one inch.
Imports
None.
Returns
The screen resolution in pixels-per-inch. The returned value is valid in both the X and Y directions.
See Also
The getScreenSize method of the Toolkit class
Example
This example method creates a Frame window which is exactly five inches wide by five inches tall.
public Frame make5by5Frame()getColorModel
ClassName
Toolkit
Purpose
Gets the ColorModel describing the color capabilities of the desktop.
Syntax
public ColorModel getColorModel();
Parameters
None.
Description
Returns the ColorModel object for the desktop. The ColorModel describes the color palette or color capabilities of the desktop.
Imports
java.awt.image.ColorModel
Returns
A ColorModel object describing the color capabilities of the desktop.
See Also
The ColorModel class
Example
This example method profiles the number of colors the desktop is capable of displaying simultaneously.
public void displaySimulColors()getFontList
ClassName
Toolkit
Purpose
Lists all the font face names available for rendering text.
Syntax
public abstract String[] getFontList();
Parameters
None.
Description
Use this method to get a list of all available fonts on the system. An array is returned, each element of which is a String containing a valid font face name. Use Font.getFont with the font face name to create a Font object for a particular face name.
Imports
None.
Returns
None.
Example
See the example Project for this chapter, FontLab, which uses getFontList to enumerate all font face names available on the local system.
getFontMetrics
ClassName
Toolkit
Purpose
Gets the FontMetrics for a particular Font as rendered on the desktop.
Syntax
public abstract FontMetrics getFontMetrics(Font font);
Parameters
Font font
The Font you want to gather metrics for.
Description
This method returns a FontMetrics object describing the metrics of a particular Font when rendered on the desktop. The Component.getFontMetrics method is actually a shallow wrapper around this method.
Imports
java.awt.FontMetrics, java.awt.Font
Returns
A FontMetrics object describing the metrics of Font font when rendered on the desktop.
Example
This example method returns the length, in pixels, of a String when displayed on the desktop using a particular Font. The Font is described only by a font face name, such as one of the elements returned by Toolkit.getFontList.
public int getStringWidthInFont(String str, String strFaceName)getDefaultToolkit
ClassName
Toolkit
Purpose
Gets the Toolkit object used by the AWT.
Syntax
public static synchronized Toolkit getDefaultToolkit();
Parameters
None.
Description
Gets the Toolkit object used by the java.awt.* packages. There is nothing stopping you from implementing another Toolkit in addition to the default Toolkit. For example, if you wanted to take advantage of some native windowing system capabilities, which are not available through Java's Toolkit object, you could implement your own and use it instead of Java's Toolkit object.
Imports
None.
Returns
The Toolkit object used within the Java API classes is returned.
Example
See the examples for the methods getFontMetrics and getScreenResolution in the Toolkit class.
getImage
ClassName
Toolkit
Purpose
To load an image from a URL and prepare it for rendering on the desktop.
Syntax
public abstract Image getImage( String filename );public abstract Image getImage( URL url );
Parameters
String filename
The full path name for a graphical format file on the local file system.
URL url
Points to an image file to be loaded by the Toolkit.
Description
This method allows any code in Java to initiate loading of an Image from a graphical image file. This graphical format file may be a location in a file on the local file system, or is indicated by a URL (available or the Internet). The first overloaded version of this method loads images from files on the local file system, and the second loads images from files available over the Internet.
Imports
java.awt.Image
Returns
An Image object will be returned by this object. The reaction of this method when the URL refers to an unsupported protocol or when the image file format is unrecognized or is unspecified. Generally, it can be assumed that null will be returned if this capability is not provided by the Toolkit.
See Also
The Image class
Example
The following sample Component loads and displays an image. A relative URL to the image to be loaded is passed to the Component's constructor. The Component acts as the ImageObserver for the Image construction process.
public class ImageComp extends ComponentprepareImage
ClassName
Toolkit
Purpose
Kick-starts the Image construction process for an Image to be displayed with a specified width and height.
Syntax
public boolean prepareImage(Image img, int width, int height, ImageObserver observer);
Parameters
Image img
The Image object to create a screen representation of.
int width
int height
The scaled size of the Image's representation.
ImageObserver observer
The ImageObserver object to receive notification of the asynchronous progress of the construction of the Image's representation.
Description
Starts construction of a screen representation of an Image object. An Image must be constructed before it can be displayed on a Component's surface. Note that when you use Graphics.drawImage with a reference to an unconstructed Image object, the Image's construction process is automatically started for you. The prepareImage method allows you to start this process before the Image is displayed on any surface.
Imports
java.awt.Image, java.awt.image.ImageObserver
Returns
True is returned if the representation of the Image object is complete. Otherwise, false is returned and the Image construction process is started.
See Also
The Image class; the ImageObserver interface; the checkImage method of the Toolkit class
Example
See the example for the checkImage method of the Toolkit class.
checkImage
ClassName
Toolkit
Purpose
To check the status of construction of an Image.
Syntax
public int checkImage(Image img, int width, int height, ImageObserver observer);
Parameters
Image img
The Image object whose status is to be checked.
int width
int height
The scaled size of the image representation being checked.
ImageObserver observer
An ImageObserver object currently being notified of the progress of construction of the Image object.
Description
Checks the status of the construction of an Image object. The ImageObserver is continuously notified about the progress of the image construction process through its updateImage method. checkImage allows non-ImageObserver objects to poll for the progress of this process.
Imports
None.
Returns
A logical ORing of the ImageObserver flags indicating what information about the Image is available. This can include one or more of the following ImageObserver values: WIDTH, HEIGHT, PROPERTIES, SOMEBITS, FRAMEBITS, ALLBITS, ERROR.
See Also
The ImageObserver interface
Example
This example prevents the Component from painting its surface until the Image construction flag ALLBITS has been passed to the ImageObserver watching the image construction process.
public MyComponent extends CanvascreateImage
ClassName
Toolkit
Purpose
Creates an in-memory Image from pixel data provided by an ImageProducer.
Syntax
public Image createImage(ImageProducer producer);
Parameters
ImageProducer producer
The ImageProducer object which will provide the data defining the resultant Image.
Description
The resultant Image will have a compatible ColorModel to the display device associated with this Component object. This method creates the Image using pixel data provided by the ImageProducer. (See Chapter 8, which describes image processing methods and techniques in Java.)
Imports
java.awt.image.ImageProducer
Returns
An Image object.
See Also
The ImageProducer class
Example
This example uses createImage along with a fictitious FakeFilter, which is supposed to be any type of ImageFilter (See Chapter 8 for a discussion of ImageProducers, ImageConsumers, and ImageFilters).
// Assume a URL has been provided for theThe SuperBible Project for this chapter is called FontLab. FontLab is a relatively simple Java application that illustrates the use of z-ordering to arrange Components within a Container. All of the FontLab classes are defined within the same .JAVA file, FontLab.java. The Project can be found on the CD that accompanies this book in the directory WHERETHEPROJECTIS.
Figure 3-10 shows the FontLab application running. One thing you may notice right away about the FontLab interface is that there are several overlapping panels in the main window. That's one of the lessons of FontLab: how to make pseudo-MDI (multi-document interface) applications. Another lesson is z-ordering of child Components.
Figure 3-10 Screenshot of the FontLab project
1. Create a file named FontLab.java. This file will hold all the code for this project.
2. The first class to create is the application class, which will implement our static main() method. Also, ensure the proper packages are imported. The code for this step is
import java.awt.*;3. Create our application's main Frame class. This Frame contains the various panels to display each Font. The constructor creates each of the display panels and adds them. The code for this step is
class FontLabFrame extends Frame4. As with all Frame windows, the FontLabFrame class must handle all WINDOW_DESTROY Events to dispose of the window. The code for the handleEvent method of the FontLabFrame class is
public boolean handleEvent(Event evt)5. When a mouse click occurs anywhere in the application, FontLabFrame should handle it. When handling a mouse click, locate the child Component on which the click occurred, then remove and re-add the associated FontDisplay panel so it is brought to the proper z-order.
public boolean mouseDown(Event evt, int x, int y)6. A FontDisplay panel displays sample text using a particular Font. The Font is given to the FontDisplay object's constructor when it is created. A toolbar is also provided so the user may change the sample text and the size it is displayed at. Creation of the toolbar and initialization of the FontDisplay's member occurs in the constructor. Here is the code:
class FontDisplay extends Panel7. Add an inset around the FontDisplay so child Components aren't butted up against the FontDisplay's borders. Here is the code:
// Return insets of 5 in all directions8. The paint method of the FontDisplay class simply draws the sample text using the indicated Font. The sample text is centered within the FontDisplay object. Here is the code:
public void paint(Graphics g)9. When the user hits the Update button on the FontDisplay, the FontDisplay receives an ACTION_EVENT, handled by the action method. Our implementation reads in the new sample text and Font size, and updates the FontDisplay's member variables accordingly. Here is the code:
// When the Update button is hit, change to new font10. Finally, implement the NullLayout class, which is a LayoutManager that essentially does nothing. This allows us to place the FontLabFrame's child Components (FontDisplay objects) in overlapping positions. Chapter 6 discusses LayoutManagers. Here is the code:
// The NullLayout is a no-op layout manager. It just leavesThe FontLab Classes
Within FontLab, there are four predefined classes. Tabele 3-3 lists the four classes and a description of each.
|
||||||||||||||
During Program Initialization
When FontLab starts up, the FontLab.main() method is run. The main() method only has three lines of code:
FontLabFrame f = new FontLabFrame('Font Lab');That is, it creates the main window, resizes it to a predefined size, shows the main frame, and quits.
Most of the initialization work is done within the FontLabFrame's constructor. That constructor has two tasks: First, it gets the list of available fonts from the Toolkit, using Toolkit.getFontList. Second, it creates a FontDisplay object for each of the available fonts, sizes it, places it, and adds it as a Component of the main frame window. Here's the code from the FontLabFrame constructor that performs those steps:
// Get the list of available fonts.The sizing of the FontLabFrame and the various FontDisplay panels is hard-coded to keep the code complexity to a minimum. What's not shown above is that the FontLabFrame sets its LayoutManager to a NullLayout object, but that also occurs within the FontLabFrame constructor.
The last step in the initialization process is the FontDisplay constructor, which is used to create each of the FontDisplay panels. As you can see in Figure 3-10, the FontDisplay panel is made up of three parts: The title at the top of the panel, the sample text in the center of the panel, and a toolbar allowing the user to write in sample text and a text size in the lower panel. The FontDisplay constructor creates these three elements before quiting.
Each FontDisplay panel is supposed to represent one of the available fonts for the system. The FontDisplay constructor takes the typeface name it is supposed to represent as the only argument. The FontDisplay stores this typeface name in a member variable, and sets its font to a 10-point Font based on this typeface name:
public FontDisplay(String strFontName)
Politica de confidentialitate | Termeni si conditii de utilizare |
Vizualizari: 939
Importanta:
Termeni si conditii de utilizare | Contact
© SCRIGROUP 2024 . All rights reserved