Component java что это такое
Перейти к содержимому

Component java что это такое

  • автор:

Events Between Java Components

A.Mahdy AbdelAziz

One of the core concepts of object orientation in Java is that every class can be considered to be a component. Components can be extended or included to form bigger components. The final application is also considered a component. Components are like Lego blocks that build up a bigger structure.

An event in Java is an action that changes the state of a component. For example, if your component is a button, then clicking on that button is an event that changes the state of the button to be clicked.

Events do not necessarily happen only on visual components. For example, you can have an event on a USB component that a device is connected. Or an event on a network component that data is transferred.

Events help to decouple the dependencies between components. Consider the following example.

Assume we have an Oven component and a Person component. They are two components that exist in parallel and work independently of one another. We should not make Person part of Oven, nor the other way around. To build a smart house, we want the Oven to prepare food once Person is hungry. Here are possible implementations:

  1. Oven checks Person in fixed, short intervals. This not only annoys Person, but is also expensive for the Oven if we want it to check on multiple instances of Person.
  2. Person comes with a public event Hungry, to which Oven is subscribed. Once Hungry is fired, Oven is notified immediately and starts preparing food.

The second solution uses the event architecture to handle the listening and communication between components efficiently and without a direct coupling between Person and Oven, because Person will fire the event, and any component Oven, Fridge, and Table can listen to that event without any special handling from the Person component.

Implementing events for a Java component can take different formats, depending on how they are expected to be handled, and the logic of the component. Here is an example showing a minimal code to implement a HungerListener in the Person component:

First, create a listener interface:

Then, in the Person class, define a list to store the listeners:

Define an API to insert a new listener:

You can create a similar API for removing a listener.

Also, add a method to trigger the action of being hungry, that notifies all the listeners about the event:

Finally, from the Oven class, add code that listens to the event and implements the action when the event is fired:

And to try it out:

For a fully decoupled code, the last section should be in an independent class that has an instance of Person and Oven, and handles the logic between them. Similarly, we can add other actions for Fridge, Table, ..etc. They all will get notified only once the Person becomesHungry.

What is a component

I listen to the podcast java posse, on this there is often discussion about components (note components are not (clearly) objects). They lament the fact that Java does not have components, and contrast with .NET that does. Components apparently makes developing applications (not just GUI apps) easier.

I can figure from the discussion certain qualities that a component has, its something to-do with decoupling (substituting one component for another is just a matter of plumbing). It has something to-do with properties, it definitely has something to-do with events and delegates.

So to the questions:

./ can anyone explain to me what a component is. (and why java beans are not components).

./ can anyone explain how they help development.

./ can anyone explain why java does not have them if they are so useful.

6 Answers 6

The general idea is that a software component can describe what its own dependencies and services are, in the form of metadata. I don’t know why you might have heard that Java does not have components, since you can certainly imagine an architecture in Java where components do describe themselves through metadata. I suppose it’s just that the Java platform definition by itself doesn’t really have a component architecture.

Update: Indeed, one need not imagine such an architecture because as others pointed out, Java Beans or Servlets could certainly be considered component-based architectures.

The term component is one of the most ambiguous and overused ones in OO.

Most people would agree that a component is made up of a group of classes, which collaborate together to implement one or more interfaces. One of the classes takes on the role of the ‘front-end’ i.e. it implements the interface but delegates the work to the other classes within the group. As you say components should be replaceable without the rest of the system knowing.

A great example of a component based architecture was COM. Its a great example because it was so heavily used and rigidly specified. But note that the need for this architecture was based on the inflexibility of the C++ compilation and deployment model.

in Java you can do an awful lot to a class without breaking binary compatability with the rest of the system. So there is not as much need to build rigid, component based architectures. But it all depends on how you define the term, e.g any project built using dependency injection could count as ‘component based’.

Although in Java beginnings the notion of component was many times related with Gui components, the generic sense of component in software engineering goes beyond that notion.

Simply put, a component is a piece of software, which is reusable. Like bricks, we combine and join them to build a whole application. The key insight of software components in modern environments is the Metadata, which describes the component’s content and enables reuse.

In 1996, the JDK 1.0 was the first managed runtime environment providing components with metadata. In this case, components are .class files containing bytecodes and metadata. Yet, and according to the Java Specification, a .class file only contains one type definition. So, to deploy a bundle of types as a component we may use a Jar archive containing several .class files.

On the other hand, in the .Net platform, which provides the same idea of reusable components, a component may contain more than one type definition. In this case a component (aka assembly in .Net) is a .dll or a .exe file.

Class Component

Класс Component является абстрактным суперклассом компонентов набора средств Abstract Window Toolkit, не связанных с меню Component Component класса также может быть расширен напрямую для создания легковесного компонента. Облегченный компонент — это компонент, не связанный с собственным окном. Напротив, тяжеловесный компонент связан с собственным окном. Метод isLightweight() можно использовать для различения двух типов компонентов.

Легкие и тяжелые компоненты могут быть смешаны в одной иерархии компонентов. Однако для правильной работы такой смешанной иерархии компонентов вся иерархия должна быть корректной. Когда иерархия становится недействительной, например, после изменения границ компонентов или добавления/удаления компонентов в/из контейнеров, вся иерархия должна быть впоследствии проверена с помощью метода Container.validate(), вызываемого для самого верхнего Container.validate() контейнера иерархия.

Serialization

Примечание . Для получения дополнительной информации о механизмах рисования, используемых AWT и Swing, включая информацию о том, как написать наиболее эффективный код рисования, см. Рисование в AWT и Swing .

Для получения подробной информации о подсистеме фокуса см. Как использовать подсистему фокуса , раздел в Учебном руководстве по Java и Спецификацию фокуса для получения дополнительной информации.

Component java что это такое

The Component class is the abstract superclass of the nonmenu-related Abstract Window Toolkit components. Class Component can also be extended directly to create a lightweight component. A lightweight component is a component that is not associated with a native window. On the contrary, a heavyweight component is associated with a native window. The isLightweight() method may be used to distinguish between the two kinds of the components.

Lightweight and heavyweight components may be mixed in a single component hierarchy. However, for correct operating of such a mixed hierarchy of components, the whole hierarchy must be valid. When the hierarchy gets invalidated, like after changing the bounds of components, or adding/removing components to/from containers, the whole hierarchy must be validated afterwards by means of the Container.validate() method invoked on the top-most invalid container of the hierarchy.

Serialization

Note: For more information on the paint mechanisms utilitized by AWT and Swing, including information on how to write the most efficient painting code, see Painting in AWT and Swing.

For details on the focus subsystem, see How to Use the Focus Subsystem, a section in The Java Tutorial, and the Focus Specification for more information.

Nested Class Summary

Nested Classes

Modifier and Type Class and Description
protected class Component.AccessibleAWTComponent

Field Summary

Fields

Modifier and Type Field and Description
protected AccessibleContext accessibleContext

Fields inherited from interface java.awt.image.ImageObserver

Constructor Summary

Constructors

Modifier Constructor and Description
protected Component ()

Method Summary

All Methods Instance Methods Concrete Methods Deprecated Methods

Modifier and Type Method and Description
boolean action (Event evt, Object what)

Methods inherited from class java.lang.Object

Field Detail

TOP_ALIGNMENT
CENTER_ALIGNMENT
BOTTOM_ALIGNMENT
LEFT_ALIGNMENT
RIGHT_ALIGNMENT
accessibleContext

Constructor Detail

Component

Method Detail

getName
setName
getParent
getPeer
setDropTarget
getDropTarget
getGraphicsConfiguration
getTreeLock
getToolkit
isValid
isDisplayable

A component is made displayable either when it is added to a displayable containment hierarchy or when its containment hierarchy is made displayable. A containment hierarchy is made displayable when its ancestor window is either packed or made visible.

A component is made undisplayable either when it is removed from a displayable containment hierarchy or when its containment hierarchy is made undisplayable. A containment hierarchy is made undisplayable when its ancestor window is disposed.

isVisible
getMousePosition

For Container s it returns a non-null value if the mouse is above the Container itself or above any of its descendants. Use Container.getMousePosition(boolean) if you need to exclude children.

Sometimes the exact mouse coordinates are not important, and the only thing that matters is whether a specific Component is under the mouse pointer. If the return value of this method is null , mouse pointer is not directly above the Component .

isShowing
  • the component has been added to a visible ScrollPane but the Component is not currently in the scroll pane’s view port.
  • the Component is obscured by another Component or Container .
isEnabled
setEnabled

Note: Disabling a lightweight component does not prevent it from receiving MouseEvents.

Note: Disabling a heavyweight container prevents all components in this container from receiving any input events. But disabling a lightweight container affects only this container.

enable
enable
disable
isDoubleBuffered
enableInputMethods
setVisible

This method changes layout-related information, and therefore, invalidates the component hierarchy.

getForeground
setForeground
isForegroundSet
getBackground
setBackground

The background color affects each component differently and the parts of the component that are affected by the background color may differ between operating systems.

isBackgroundSet
getFont
setFont

This method changes layout-related information, and therefore, invalidates the component hierarchy.

isFontSet
getLocale
setLocale

This method changes layout-related information, and therefore, invalidates the component hierarchy.

getColorModel
getLocation

Due to the asynchronous nature of native event handling, this method can return outdated values (for instance, after several calls of setLocation() in rapid succession). For this reason, the recommended method of obtaining a component’s position is within java.awt.event.ComponentListener.componentMoved() , which is called after the operating system has finished moving the component.

getLocationOnScreen
location
setLocation

This method changes layout-related information, and therefore, invalidates the component hierarchy.

setLocation

This method changes layout-related information, and therefore, invalidates the component hierarchy.

getSize
setSize

This method changes layout-related information, and therefore, invalidates the component hierarchy.

resize
setSize

This method changes layout-related information, and therefore, invalidates the component hierarchy.

resize
getBounds
bounds
setBounds

This method changes layout-related information, and therefore, invalidates the component hierarchy.

reshape
setBounds

This method changes layout-related information, and therefore, invalidates the component hierarchy.

getWidth
getHeight
getBounds
getSize
getLocation
isOpaque

An opaque component paints every pixel within its rectangular region. A non-opaque component paints only some of its pixels, allowing the pixels underneath it to «show through». A component that does not fully paint its pixels therefore provides a degree of transparency.

Subclasses that guarantee to always completely paint their contents should override this method and return true.

isLightweight

This method will always return false if this component is not displayable because it is impossible to determine the weight of an undisplayable component.

setPreferredSize
isPreferredSizeSet
getPreferredSize
preferredSize
setMinimumSize
isMinimumSizeSet
getMinimumSize
minimumSize
setMaximumSize
isMaximumSizeSet
getMaximumSize
getAlignmentX
getAlignmentY
getBaseline

The default implementation returns -1. Subclasses that support baseline should override appropriately. If a value >= 0 is returned, then the component has a valid baseline for any size >= the minimum size and getBaselineResizeBehavior can be used to determine how the baseline changes with size.

getBaselineResizeBehavior

The default implementation returns BaselineResizeBehavior.OTHER . Subclasses that have a baseline should override appropriately. Subclasses should never return null ; if the baseline can not be calculated return BaselineResizeBehavior.OTHER . Callers should first ask for the baseline using getBaseline and if a value >= 0 is returned use this method. It is acceptable for this method to return a value other than BaselineResizeBehavior.OTHER even if getBaseline returns a value less than 0.

doLayout
layout
validate

The meaning of the term validating is defined by the ancestors of this class. See Container.validate() for more details.

invalidate

By default, all the ancestors of the component up to the top-most container of the hierarchy are marked invalid. If the java.awt.smartInvalidate system property is set to true , invalidation stops on the nearest validate root of this component. 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.g. setting the bounds of the component, or adding the component to a container).

This method might be called often, so it should work fast.

revalidate

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.

getGraphics
getFontMetrics
setCursor

The method may have no visual effect if the Java platform implementation and/or the native system do not support changing the mouse cursor shape.

getCursor
isCursorSet
paint

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.paint(g) .

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.

Note: For more information on the paint mechanisms utilitized by AWT and Swing, including information on how to write the most efficient painting code, see Painting in AWT and Swing.

update

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.update(g) , or call paint(g) directly from their update method.

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.

Note: For more information on the paint mechanisms utilitized by AWT and Swing, including information on how to write the most efficient painting code, see Painting in AWT and Swing.

paintAll

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.

repaint

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.

Note: For more information on the paint mechanisms utilitized by AWT and Swing, including information on how to write the most efficient painting code, see Painting in AWT and Swing.

repaint

Note: For more information on the paint mechanisms utilitized by AWT and Swing, including information on how to write the most efficient painting code, see Painting in AWT and Swing.

repaint

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.

Note: For more information on the paint mechanisms utilitized by AWT and Swing, including information on how to write the most efficient painting code, see Painting in AWT and Swing.

repaint

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.

Note: For more information on the paint mechanisms utilitized by AWT and Swing, including information on how to write the most efficient painting code, see Painting in AWT and Swing.

print

The default implementation of this method calls the paint method.

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.

printAll

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.

imageUpdate

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.image.incrementaldraw is missing or has the value true , the image is incrementally drawn. 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.image.redrawrate is interpreted as an integer to give the maximum redraw rate, in milliseconds. If the system property is missing or cannot be interpreted as an integer, the redraw rate is once every 100ms.

The interpretation of the x , y , width , and height arguments depends on the value of the infoflags argument.

createImage
createImage
createVolatileImage
createVolatileImage
prepareImage
prepareImage

The image data is downloaded asynchronously in another thread, and an appropriately scaled screen representation of the image is generated.

checkImage

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.

checkImage

This method does not cause the image to begin loading. An application must use the prepareImage method to force the loading of an 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.

Information on the flags returned by this method can be found with the discussion of the ImageObserver interface.

setIgnoreRepaint

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.

getIgnoreRepaint
contains
inside
contains
getComponentAt

The locate method of Component simply returns the component itself if the (x, y) coordinate location is inside its bounding box, and null otherwise.

locate
getComponentAt
deliverEvent
dispatchEvent
postEvent
addComponentListener

Refer to AWT Threading Issues for details on AWT’s threading model.

removeComponentListener

Refer to AWT Threading Issues for details on AWT’s threading model.

getComponentListeners
addFocusListener

Refer to AWT Threading Issues for details on AWT’s threading model.

removeFocusListener

Refer to AWT Threading Issues for details on AWT’s threading model.

getFocusListeners
addHierarchyListener

Refer to AWT Threading Issues for details on AWT’s threading model.

removeHierarchyListener

Refer to AWT Threading Issues for details on AWT’s threading model.

getHierarchyListeners
addHierarchyBoundsListener

Refer to AWT Threading Issues for details on AWT’s threading model.

removeHierarchyBoundsListener

Refer to AWT Threading Issues for details on AWT’s threading model.

getHierarchyBoundsListeners
addKeyListener

Refer to AWT Threading Issues for details on AWT’s threading model.

removeKeyListener

Refer to AWT Threading Issues for details on AWT’s threading model.

getKeyListeners
addMouseListener

Refer to AWT Threading Issues for details on AWT’s threading model.

removeMouseListener

Refer to AWT Threading Issues for details on AWT’s threading model.

getMouseListeners
addMouseMotionListener

Refer to AWT Threading Issues for details on AWT’s threading model.

removeMouseMotionListener

Refer to AWT Threading Issues for details on AWT’s threading model.

getMouseMotionListeners
addMouseWheelListener

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.

Refer to AWT Threading Issues for details on AWT’s threading model.

removeMouseWheelListener

Refer to AWT Threading Issues for details on AWT’s threading model.

getMouseWheelListeners
addInputMethodListener

Refer to AWT Threading Issues for details on AWT’s threading model.

removeInputMethodListener

Refer to AWT Threading Issues for details on AWT’s threading model.

getInputMethodListeners
getListeners

You can specify the listenerType argument with a class literal, such as FooListener.class . For example, you can query a Component c for its mouse listeners with the following code: If no such listeners exist, this method returns an empty array.

getInputMethodRequests
getInputContext
enableEvents

Event types are automatically enabled when a listener for that event type is added to the component.

This method only needs to be invoked by subclasses of Component which desire to have the specified event types delivered to processEvent regardless of whether or not a listener is registered.

disableEvents
coalesceEvents

This implementation of coalesceEvents coalesces two event types: mouse move (and drag) events, and paint (and update) events. For mouse move events the last event is always returned, causing intermediate moves to be discarded. For paint events, the new event is coalesced into a complex RepaintArea in the peer. The new AWTEvent is always returned.

processEvent

Note that if the event parameter is null the behavior is unspecified and may result in an exception.

processComponentEvent
  • A ComponentListener object is registered via addComponentListener .
  • Component events are enabled via enableEvents .

Note that if the event parameter is null the behavior is unspecified and may result in an exception.

processFocusEvent
  • A FocusListener object is registered via addFocusListener .
  • Focus events are enabled via enableEvents .

If focus events are enabled for a Component , the current KeyboardFocusManager determines whether or not a focus event should be dispatched to registered FocusListener objects. If the events are to be dispatched, the KeyboardFocusManager calls the Component ‘s dispatchEvent method, which results in a call to the Component ‘s processFocusEvent method.

If focus events are enabled for a Component , calling the Component ‘s dispatchEvent method with a FocusEvent as the argument will result in a call to the Component ‘s processFocusEvent method regardless of the current KeyboardFocusManager .

Note that if the event parameter is null the behavior is unspecified and may result in an exception.

processKeyEvent
  • A KeyListener object is registered via addKeyListener .
  • Key events are enabled via enableEvents .

If key events are enabled for a Component , the current KeyboardFocusManager determines whether or not a key event should be dispatched to registered KeyListener objects. The DefaultKeyboardFocusManager will not dispatch key events to a Component that is not the focus owner or is not showing.

As of J2SE 1.4, KeyEvent s are redirected to the focus owner. Please see the Focus Specification for further information.

Calling a Component ‘s dispatchEvent method with a KeyEvent as the argument will result in a call to the Component ‘s processKeyEvent method regardless of the current KeyboardFocusManager as long as the component is showing, focused, and enabled, and key events are enabled on it.

If the event parameter is null the behavior is unspecified and may result in an exception.

processMouseEvent
  • A MouseListener object is registered via addMouseListener .
  • Mouse events are enabled via enableEvents .

Note that if the event parameter is null the behavior is unspecified and may result in an exception.

processMouseMotionEvent
  • A MouseMotionListener object is registered via addMouseMotionListener .
  • Mouse motion events are enabled via enableEvents .

Note that if the event parameter is null the behavior is unspecified and may result in an exception.

processMouseWheelEvent
  • A MouseWheelListener object is registered via addMouseWheelListener .
  • Mouse wheel events are enabled via enableEvents .

For information on how mouse wheel events are dispatched, see the class description for MouseWheelEvent .

Note that if the event parameter is null the behavior is unspecified and may result in an exception.

processInputMethodEvent
  • An InputMethodListener object is registered via addInputMethodListener .
  • Input method events are enabled via enableEvents .

Note that if the event parameter is null the behavior is unspecified and may result in an exception.

processHierarchyEvent
  • An HierarchyListener object is registered via addHierarchyListener .
  • Hierarchy events are enabled via enableEvents .

Note that if the event parameter is null the behavior is unspecified and may result in an exception.

processHierarchyBoundsEvent
  • An HierarchyBoundsListener object is registered via addHierarchyBoundsListener .
  • Hierarchy bounds events are enabled via enableEvents .

Note that if the event parameter is null the behavior is unspecified and may result in an exception.

handleEvent
mouseDown
mouseDrag
mouseUp
mouseMove
mouseEnter
mouseExit
keyDown
keyUp
action
addNotify

This method changes layout-related information, and therefore, invalidates the component hierarchy.

removeNotify

This method is called by the toolkit internally and should not be called directly by programs. Code overriding this method should call super.removeNotify as the first line of the overriding method.

gotFocus
lostFocus
isFocusTraversable
isFocusable
setFocusable
setFocusTraversalKeys

The default values for a Component’s focus traversal keys are implementation-dependent. Sun recommends that all implementations for a particular native platform use the same default values. The recommendations for Windows and Unix are listed below. These recommendations are used in the Sun AWT implementations.

Identifier Meaning Default
KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS Normal forward keyboard traversal TAB on KEY_PRESSED, CTRL-TAB on KEY_PRESSED
KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS Normal reverse keyboard traversal SHIFT-TAB on KEY_PRESSED, CTRL-SHIFT-TAB on KEY_PRESSED
KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS Go up one focus traversal cycle none

To disable a traversal key, use an empty Set; Collections.EMPTY_SET is recommended.

Using the AWTKeyStroke API, client code can specify on which of two specific KeyEvents, KEY_PRESSED or KEY_RELEASED, the focus traversal operation will occur. Regardless of which KeyEvent is specified, however, all KeyEvents related to the focus traversal key, including the associated KEY_TYPED event, will be consumed, and will not be dispatched to any Component. It is a runtime error to specify a KEY_TYPED event as mapping to a focus traversal operation, or to map the same event to multiple default focus traversal operations.

If a value of null is specified for the Set, this Component inherits the Set from its parent. If all ancestors of this Component have null specified for the Set, then the current KeyboardFocusManager’s default Set is used.

This method may throw a ClassCastException if any Object in keystrokes is not an AWTKeyStroke .

getFocusTraversalKeys

If a Set of traversal keys has not been explicitly defined for this Component, then this Component’s parent’s Set is returned. If no Set has been explicitly defined for any of this Component’s ancestors, then the current KeyboardFocusManager’s default Set is returned.

areFocusTraversalKeysSet
setFocusTraversalKeysEnabled
getFocusTraversalKeysEnabled
requestFocus

This method cannot be used to set the focus owner to no Component at all. Use KeyboardFocusManager.clearGlobalFocusOwner() instead.

Because the focus behavior of this method is platform-dependent, developers are strongly encouraged to use requestFocusInWindow when possible.

Note: Not all focus transfers result from invoking this method. As such, a component may receive focus without this or any of the other requestFocus methods of Component being invoked.

requestFocus

This method returns a boolean value. If false is returned, the request is guaranteed to fail. If true is returned, the request will succeed unless it is vetoed, or an extraordinary event, such as disposal of the component’s peer, occurs before the request can be granted by the native windowing system. Again, while a return value of true indicates that the request is likely to succeed, developers must never assume that this component is the focus owner until this component receives a FOCUS_GAINED event.

This method cannot be used to set the focus owner to no component at all. Use KeyboardFocusManager.clearGlobalFocusOwner instead.

Because the focus behavior of this method is platform-dependent, developers are strongly encouraged to use requestFocusInWindow when possible.

Every effort will be made to ensure that FocusEvent s generated as a result of this request will have the specified temporary value. However, because specifying an arbitrary temporary state may not be implementable on all native windowing systems, correct behavior for this method can be guaranteed only for lightweight Component s. This method is not intended for general use, but exists instead as a hook for lightweight component libraries, such as Swing.

Note: Not all focus transfers result from invoking this method. As such, a component may receive focus without this or any of the other requestFocus methods of Component being invoked.

requestFocusInWindow

This method returns a boolean value. If false is returned, the request is guaranteed to fail. If true is returned, the request will succeed unless it is vetoed, or an extraordinary event, such as disposal of the Component’s peer, occurs before the request can be granted by the native windowing system. Again, while a return value of true indicates that the request is likely to succeed, developers must never assume that this Component is the focus owner until this Component receives a FOCUS_GAINED event.

This method cannot be used to set the focus owner to no Component at all. Use KeyboardFocusManager.clearGlobalFocusOwner() instead.

The focus behavior of this method can be implemented uniformly across platforms, and thus developers are strongly encouraged to use this method over requestFocus when possible. Code which relies on requestFocus may exhibit different focus behavior on different platforms.

Note: Not all focus transfers result from invoking this method. As such, a component may receive focus without this or any of the other requestFocus methods of Component being invoked.

requestFocusInWindow

This method returns a boolean value. If false is returned, the request is guaranteed to fail. If true is returned, the request will succeed unless it is vetoed, or an extraordinary event, such as disposal of the component’s peer, occurs before the request can be granted by the native windowing system. Again, while a return value of true indicates that the request is likely to succeed, developers must never assume that this component is the focus owner until this component receives a FOCUS_GAINED event.

This method cannot be used to set the focus owner to no component at all. Use KeyboardFocusManager.clearGlobalFocusOwner instead.

The focus behavior of this method can be implemented uniformly across platforms, and thus developers are strongly encouraged to use this method over requestFocus when possible. Code which relies on requestFocus may exhibit different focus behavior on different platforms.

Every effort will be made to ensure that FocusEvent s generated as a result of this request will have the specified temporary value. However, because specifying an arbitrary temporary state may not be implementable on all native windowing systems, correct behavior for this method can be guaranteed only for lightweight components. This method is not intended for general use, but exists instead as a hook for lightweight component libraries, such as Swing.

Note: Not all focus transfers result from invoking this method. As such, a component may receive focus without this or any of the other requestFocus methods of Component being invoked.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *