The purpose of the peer classes is to bridge the gap between the AWT classes and the underlying platform-specific UI widgets. By using a peer, the AWT provides a uniform programming interface across all platforms. The peer classes are rarely used directly in Java programming, except when porting the AWT to other platforms. Why Are Image Buttons Hard? If you were to compile a list of language features that Java users would like to see in a 1.
An image button is a button that has an image on its face instead of text. The reason the AWT doesn't have image buttons has to do with the nature of Java itself. You can change the behavior of the Button class, but not its associated peer. One possible solution would be to create an image button by extending some class other than Button. You could derive such a class from Canvas. You would need to create multiple images to represent the up and down states of the button and switch them and repaint when the user clicked in the Canvas.
The problem is that such a button would look exactly the same on every platform rather than looking like a native implementation of an image button. New Components from Old When you design a user interface, you use the widgets provided in the Toolkit as the basic building blocks. Sometimes the design calls for a control that is just slightly different from the AWT version. Rather than try to develop new controls, you modify the existing controls in the AWT.
To accomplish this, you use a method called subclassing. In object oriented terminology, this technique is often called class derivation or inheritance. The class will have a list of acceptable entries and users will only be allowed to enter values from this list. This control allows you to limit the possible inputs from the user and to anticipate the user's input.
When the user enters a character, you try to determine which string they are typing and fill in the blank for them. Start with a list of valid strings. When the user enters a character, you catch the key down Event. At this point, the bulk of the work begins. You must look at the text already in the control and determine whether the new keystroke is valid. If it so, add it to the control and find the best match for the entered text.
When you add the string to the control, you select the portion that the user did not type. So if the user types s and the matching string is spray , the last three letters ray are selected. If the user types a character other than J nothing happens because all the valid strings begin with J. When the user types a J , the control displays the J and the remainder of the first matching string in alphabetical order-in this case Janice. Figures 9. Janice is displayed and the anice is selected.
Janice is still displayed, but now the nice is selected. Nothing happens since none of the valid strings begin with Jad. The control displays Jason with the on selected. As Figures 9. The new control still takes input from the user, but it now anticipates the user's input.
This function means that less typing is necessary to enter the desired string. You have retained the functionality of delete, backspace, and other special keystrokes. These keys operate in the control just like they do in the AWT version.
To use one, you simply create it and add it to your layout. When you want to get the data that the user has entered, simply call the getText method. The control must know what strings to accept and how to interpret keystrokes. Our enhanced TextField should also be able to anticipate what the user is entering and display the best match string. Text-matching algorithms must deal with the issue of case-sensitivity.
In other words, does the string "Jennifer" match "jennifer"? Your control enables you to be either case-sensitive or case-insensitive, which makes the control more versatile, but requires some extra processing. You let the class store the information it needs by adding the following instance variables: String[] strings ; boolean caseSensitive ; int pos ; The strings variable is used to store all the acceptable string values. Eventually, you will sort this array so your matches display in alphabetical order.
The caseSensitive variable is a flag that indicates whether the string matching you do will be case-sensitive. You need to set this variable whenever you create an instance of the SelfValidatingTextField class. During the data validation, you use the variable to determine whether to accept a given keystroke.
The pos variable is used by the class to keep track of the position of the last character entered by the user. This information becomes important when you display the best match string for a given input. You will need to update pos whenever you get input from the user.
The chars parameter is used to call the overloaded TextField constructor. The specific constructor you call is TextField int n , which creates a TextField big enough to hold n characters. The call to the parent class constructor looks like super chars ; This statement invokes a super class constructor. Because the super class is TextField , the TextField int n constructor is called.
The next three statements in the constructor initialize the class instance variables. You pass the values for strings and caseSensitive into the constructor. Returns: true if this component has a lightweight peer; false if it has a native peer or no peer Since: 1. Subsequent calls to getPreferredSize will always return this value. Setting the preferred size to null restores the default behavior.
Parameters: preferredSize - The new preferred size, or null Since: 1. Returns: true if setPreferredSize has been invoked with a non-null value. Subsequent calls to getMinimumSize will always return this value.
Setting the minimum size to null restores the default behavior. Parameters: minimumSize - the new minimum size of this component Since: 1. Returns: true if setMinimumSize has been invoked with a non-null value.
Subsequent calls to getMaximumSize will always return this value. Setting the maximum size to null restores the default behavior. Parameters: maximumSize - a Dimension containing the desired maximum allowable size Since: 1. Returns: true if maximumSize is non- null , false otherwise Since: 1.
This specifies how the component would like to be aligned relative to other components. The value should be a number between 0 and 1 where 0 represents alignment along the origin, 1 is aligned the furthest away from the origin, 0. The baseline is measured from the top of the component. This method is primarily meant for LayoutManager s to align components along their baseline. A return value less than 0 indicates this component does not have a reasonable baseline and that LayoutManager s should not align this component on its baseline.
The default implementation returns Subclasses that support baseline should override appropriately. This method is primarily meant for layout managers and GUI builders. The default implementation returns BaselineResizeBehavior. Subclasses that have a baseline should override appropriately. Subclasses should never return null ; if the baseline can not be calculated return BaselineResizeBehavior. It is acceptable for this method to return a value other than BaselineResizeBehavior.
Returns: an enum indicating how the baseline changes as the component size changes Since: 1. This is usually called when the component more specifically, container is validated. The meaning of the term validating is defined by the ancestors of this class.
See Container. Since: JDK1. By default, all the ancestors of the component up to the top-most container of the hierarchy are marked invalid. If the java. Marking a container invalid indicates that the container needs to be laid out. This method is called automatically when any layout-related information changes e. This method might be called often, so it should work fast. This method first invalidates the component hierarchy starting from this component up to the nearest validate root.
Afterwards, the component hierarchy is validated starting from the nearest validate root. This is a convenience method supposed to help application developers avoid looking for validate roots manually. Basically, it's equivalent to first calling the invalidate method on this component, and then calling the validate method on the nearest validate root.
This method will return null if this component is currently not displayable. Returns: a graphics context for this component, or null if it has none Since: JDK1. Warning: Since Font metrics are affected by the FontRenderContext and this method does not provide one, it can return only metrics for the default render context which may not match that used when rendering on the Component if Graphics2D functionality is being used.
Instead metrics can be obtained at rendering time by calling Graphics. Parameters: font - the font for which font metrics is to be obtained Returns: the font metrics for font Since: JDK1. This cursor image is displayed when the contains method for this component returns true for the current cursor location, and this Component is visible, displayable, and enabled.
Setting the cursor of a Container causes that cursor to be displayed within all of the container's subcomponents, except for those that have a non- null cursor. Parameters: cursor - One of the constants defined by the Cursor class; if this parameter is null then this component will inherit the cursor of its parent Since: JDK1.
Image, java. Point, java. If the component does not have a cursor set, the cursor of its parent is returned. If no cursor is set in the entire hierarchy, Cursor. If this method returns false , this Component is inheriting its cursor from an ancestor. Returns: true if the cursor has been explicitly set for this Component; false otherwise. This method is called when the contents of the component should be painted; such as when the component is first being shown or is damaged and in need of repair.
The clip rectangle in the Graphics parameter is set to the area which needs to be painted. Subclasses of Component that override this method need not call super. For performance reasons, Component s with zero width or height aren't considered to need painting when they are first shown, and also aren't considered to need repair.
Parameters: g - the graphics context to use for painting Since: JDK1. Graphics update public void update Graphics g Updates this component. If this component is not a lightweight component, the AWT calls the update method in response to a call to repaint.
You can assume that the background is not cleared. The update method of Component calls this component's paint method to redraw this component. This method is commonly overridden by subclasses which need to do additional work in response to a call to repaint. Subclasses of Component that override this method should either call super. The origin of the graphics context, its 0 , 0 coordinate point, is the top-left corner of this component.
The clipping region of the graphics context is the bounding rectangle of this component. Parameters: g - the specified context to use for updating Since: JDK1. Graphics , repaint paintAll public void paintAll Graphics g Paints this component and all of its subcomponents. Graphics repaint public void repaint Repaints this component. If this component is a lightweight component, this method causes a call to this component's paint method as soon as possible.
Otherwise, this method causes a call to this component's update method as soon as possible. If this component is a lightweight component, this results in a call to paint within tm milliseconds.
Parameters: tm - maximum time in milliseconds before update Since: JDK1. Graphics , update Graphics repaint public void repaint int x, int y, int width, int height Repaints the specified rectangle of this component. Parameters: x - the x coordinate y - the y coordinate width - the width height - the height Since: JDK1. If this component is a lightweight component, this method causes a call to this component's paint method.
Otherwise, this method causes a call to this component's update method. Parameters: tm - maximum time in milliseconds before update x - the x coordinate y - the y coordinate width - the width height - the height Since: JDK1. Applications should override this method for components that must do special processing before being printed or should be printed differently than they are painted. The default implementation of this method calls the paint method. Parameters: g - the graphics context to use for printing Since: JDK1.
This imageUpdate method of an ImageObserver is called when more information about an image which had been previously requested using an asynchronous routine such as the drawImage method of Graphics becomes available.
See the definition of imageUpdate for more information on this method and its arguments. The imageUpdate method of Component incrementally draws an image on the component as more of the bits of the image are available.
If the system property awt. If the system property has any other value, then the image is not drawn until it has been completely loaded. Also, if incremental drawing is in effect, the value of the system property awt.
If the system property is missing or cannot be interpreted as an integer, the redraw rate is once every ms. The interpretation of the x , y , width , and height arguments depends on the value of the infoflags argument. Specified by: imageUpdate in interface ImageObserver Parameters: img - the image being observed infoflags - see imageUpdate for more information x - the x coordinate y - the y coordinate w - the width h - the height Returns: false if the infoflags indicate that the image is completely loaded; true otherwise.
ImageObserver , Graphics. ImageObserver , ImageObserver. Image, int, int, int, int, int createImage public Image createImage ImageProducer producer Creates an image from the specified image producer. Parameters: width - the specified width height - the specified height Returns: an off-screen drawable image, which can be used for double buffering.
The return value may be null if the component is not displayable. This will always happen if GraphicsEnvironment. Parameters: width - the specified width. Returns: an off-screen drawable image, which can be used for double buffering. The contents of this image may be lost at any time due to operating system issues, so the image must be managed via the VolatileImage interface.
The image data is downloaded asynchronously in another thread and the appropriate screen representation of the image is generated. Parameters: image - the Image for which to prepare a screen representation observer - the ImageObserver object to be notified as the image is being prepared Returns: true if the image has already been fully prepared; false otherwise Since: JDK1.
The image data is downloaded asynchronously in another thread, and an appropriately scaled screen representation of the image is generated. Parameters: image - the instance of Image for which to prepare a screen representation width - the width of the desired screen representation height - the height of the desired screen representation observer - the ImageObserver object to be notified as the image is being prepared Returns: true if the image has already been fully prepared; false otherwise Since: JDK1.
This method does not cause the image to begin loading. An application must use the prepareImage method to force the loading of an image. Information on the flags returned by this method can be found with the discussion of the ImageObserver interface. Parameters: image - the Image object whose status is being checked observer - the ImageObserver object to be notified as the image is being prepared Returns: the bitwise inclusive OR of ImageObserver flags indicating what information about the image is currently available Since: JDK1.
ImageObserver , Toolkit. ImageObserver , ImageObserver checkImage public int checkImage Image image, int width, int height, ImageObserver observer Returns the status of the construction of a screen representation of the specified image. The checkImage method of Component calls its peer's checkImage method to calculate the flags.
If this component does not yet have a peer, the component's toolkit's checkImage method is called instead. Parameters: image - the Image object whose status is being checked width - the width of the scaled version whose status is to be checked height - the height of the scaled version whose status is to be checked observer - the ImageObserver object to be notified as the image is being prepared Returns: the bitwise inclusive OR of ImageObserver flags indicating what information about the image is currently available Since: JDK1.
ImageObserver , ImageObserver setIgnoreRepaint public void setIgnoreRepaint boolean ignoreRepaint Sets whether or not paint messages received from the operating system should be ignored. This does not affect paint events generated in software by the AWT, unless they are an immediate response to an OS-level paint message. This is useful, for example, if running under full-screen mode and better performance is desired, or if page-flipping is used as the buffer strategy.
Window getIgnoreRepaint public boolean getIgnoreRepaint Returns: whether or not paint messages received from the operating system should be ignored. Parameters: x - the x coordinate of the point y - the y coordinate of the point Since: JDK1. This method only looks one level deep. If the point x , y is inside a subcomponent that itself has subcomponents, it does not go looking down the subcomponent tree. The locate method of Component simply returns the component itself if the x , y coordinate location is inside its bounding box, and null otherwise.
Parameters: x - the x coordinate y - the y coordinate Returns: the component or subcomponent that contains the x , y location; null if the location is outside this component Since: JDK1. Parameters: p - the point Since: JDK1. Calls processEvent before returning for 1. Specified by: postEvent in interface MenuContainer addComponentListener public void addComponentListener ComponentListener l Adds the specified component listener to receive component events from this component.
If listener l is null , no exception is thrown and no action is performed. Parameters: l - the component listener Since: JDK1.
ComponentListener , getComponentListeners removeComponentListener public void removeComponentListener ComponentListener l Removes the specified component listener so that it no longer receives component events from this component. This method performs no function, nor does it throw an exception, if the listener specified by the argument was not previously added to this component.
ComponentListener , getComponentListeners getComponentListeners public ComponentListener [] getComponentListeners Returns an array of all the component listeners registered on this component. Returns: all of this comonent's ComponentListener s or an empty array if no component listeners are currently registered Since: 1. ComponentListener , removeComponentListener java.
ComponentListener addFocusListener public void addFocusListener FocusListener l Adds the specified focus listener to receive focus events from this component when this component gains input focus.
Parameters: l - the focus listener Since: JDK1. FocusListener , getFocusListeners removeFocusListener public void removeFocusListener FocusListener l Removes the specified focus listener so that it no longer receives focus events from this component. Returns: all of this component's FocusListener s or an empty array if no component listeners are currently registered Since: 1. FocusListener , removeFocusListener java. FocusListener addHierarchyListener public void addHierarchyListener HierarchyListener l Adds the specified hierarchy listener to receive hierarchy changed events from this component when the hierarchy to which this container belongs changes.
Parameters: l - the hierarchy listener Since: 1. HierarchyListener , getHierarchyListeners removeHierarchyListener public void removeHierarchyListener HierarchyListener l Removes the specified hierarchy listener so that it no longer receives hierarchy changed events from this component.
HierarchyListener , getHierarchyListeners getHierarchyListeners public HierarchyListener [] getHierarchyListeners Returns an array of all the hierarchy listeners registered on this component. Returns: all of this component's HierarchyListener s or an empty array if no hierarchy listeners are currently registered Since: 1. HierarchyListener , removeHierarchyListener java. HierarchyListener addHierarchyBoundsListener public void addHierarchyBoundsListener HierarchyBoundsListener l Adds the specified hierarchy bounds listener to receive hierarchy bounds events from this component when the hierarchy to which this container belongs changes.
Parameters: l - the hierarchy bounds listener Since: 1. HierarchyBoundsListener , getHierarchyBoundsListeners removeHierarchyBoundsListener public void removeHierarchyBoundsListener HierarchyBoundsListener l Removes the specified hierarchy bounds listener so that it no longer receives hierarchy bounds events from this component.
Returns: all of this component's HierarchyBoundsListener s or an empty array if no hierarchy bounds listeners are currently registered Since: 1. If l is null, no exception is thrown and no action is performed. Parameters: l - the key listener.
KeyListener , getKeyListeners removeKeyListener public void removeKeyListener KeyListener l Removes the specified key listener so that it no longer receives key events from this component.
Parameters: l - the key listener Since: JDK1. Returns: all of this component's KeyListener s or an empty array if no key listeners are currently registered Since: 1. KeyListener , removeKeyListener java. KeyListener addMouseListener public void addMouseListener MouseListener l Adds the specified mouse listener to receive mouse events from this component.
Parameters: l - the mouse listener Since: JDK1. MouseListener , getMouseListeners removeMouseListener public void removeMouseListener MouseListener l Removes the specified mouse listener so that it no longer receives mouse events from this component.
Returns: all of this component's MouseListener s or an empty array if no mouse listeners are currently registered Since: 1. MouseListener , removeMouseListener java. Parameters: l - the mouse motion listener Since: JDK1. Returns: all of this component's MouseMotionListener s or an empty array if no mouse motion listeners are currently registered Since: 1. Containers also receive mouse wheel events from sub-components.
For information on how mouse wheel events are dispatched, see the class description for MouseWheelEvent. If l is null , no exception is thrown and no action is performed. Parameters: l - the mouse wheel listener Since: 1. Parameters: l - the mouse wheel listener. Returns: all of this component's MouseWheelListener s or an empty array if no mouse wheel listeners are currently registered Since: 1.
A component will only receive input method events from input methods if it also overrides getInputMethodRequests to return an InputMethodRequests instance. Parameters: l - the input method listener Since: 1. Returns: all of this component's InputMethodListener s or an empty array if no input method listeners are currently registered Since: 1. Foo Listener s are registered using the add Foo Listener method. You can specify the listenerType argument with a class literal, such as Foo Listener. Parameters: listenerType - the type of listeners requested; this parameter should specify an interface that descends from java.
EventListener Returns: an array of all objects registered as Foo Listener s on this component, or an empty array if no such listeners have been added Throws: ClassCastException - if listenerType doesn't specify a class or interface that implements java. A component that supports on-the-spot text input must override this method to return an InputMethodRequests instance.
At the same time, it also has to handle input method events. Here is a much better looking version of our 'summation' program. We'll look a little more thoroughly into layout managers and panels in the next lecture. We'll also start creating Applets soon, and see how to easly turn a stand-along program into a web-enabled applet and vica versa. The rest of the program has not really changed too much and is easy to understand. Here's a question, though: What happens if a non-integer is entered into the TextField.
Using the Java generics approach has worked very well. If I were going to rewrite this in Scala, I would probably do something with traits instead of creating a delegate class. The traits could "add" the delete functionality to the JInternalFrame derived concrete class, for example. It's not really the best way to do things but in your case it works. You should really split your method in two, one for the I behavior and another for the Component behavior.
It's ugly, but you can use generics and constrain the method parameter to extend the class and implement the interface. Here's a complete example:. In this case, if you want to do as you describe, it probably makes sense to create a class C that implements the common functionality between A and B from which both A and B can extend. This way, you can just pass class C as the argument to the D.
Without knowing the exact classes, it's hard to make this call definitively. I'm just basing it on the function that you're trying to create. Since the D. Stack Overflow for Teams — Collaborate and share knowledge with a private group. Create a free Team What is Teams? Collectives on Stack Overflow.
Learn more. Asked 11 years, 2 months ago. Active 8 years, 4 months ago. Viewed 2k times.
0コメント