PROGRAMMATION SWING ET XML

I. UTILISATION DES COMPOSANTS SWING


    A l'exception des conteneurs racines, tous les composants Swing dont le nom commence par "J" descendent de la classe JComponent. Par exemple la classe JPanel, JScroolPane, JButton et JTable héritent toutes de la classe JComponent. Cependant, ce n'est pas  le cas de la classe JFrame car elle implémente un conteneur racine.     La classe JComponent étend la classe Container, qui hérite elle meme de la classe . La classe Component contient tout depuis le support de l'agencement, en passant par l'affichage et les événements. La classe Container fournit la possibilité d'ajouter des composants et de les agencer. Ce chapitre contient des tables décrivant succintement les méthodes les plus utilisées des classes Component et Container.

2. Les caractéristiques de la classe JComponent.

La classe JComponent fournit les fonctionnalités suivantes à ses descendants :
Les bulles d'aide
    En fixant un texte avec la méthode setToolTipText, vous pouvez fournir une aide aux utilisateurs d'un composant. Quand le curseur effectuera une pause sur le composant, le texte spécifié sera affiché dans une petite fenetre qui apparaitra près du composant. Pour plus de détail sur cette fonctionnalités, consultez : Comment utiliser les bulles d'aides.
Les bordures
    La méthode setBorder nous permet de spécifier la bordure qu'affichera un composant le long de ses contours. Pour plus de détails la dessus, consultez : Comment utiliser les bordures.
Les raccourcis clavier
    L'utilisation de la méthode registerKeyboardAction, nous permet de fournir à l'utilisateur, la possibilité d'utiliser le clavier à la place de la souris pour manipuler l'interface graphique.

Note:  Quelques classes fournissent des méthodes facilitant la gestion des raccourcis claviers. Par exemple, la classe AbstractButton supporte la méthode setMnemonic, qui nous permet de spécifier la touche qui, en combinaison avec la touche modificatrice dépendante du Look & Feel, provoquera le déclenchement de l'action associée au boutton concerné. Pour voir quelques exemples d'utilisation de raccourcis claviers, consultez Comment utiliser les boutons, les boites de choix, et les boutons radios
    La combinaison d'un caractère et d'une touche modificatrice que l'utilisateur doit presser simultanément pour effectuer une action est représentée par un objet KeyStroke. L'événement résultant doit etre traité par un ActionListener. Chaque raccourci clavier fonctionne selon les trois conditions suivantes : seulement quand le composant courant détient le focus, seulement quand le composant ou l'un de ses conteneurs à le focus ou n'importe quand lorsqu'un des composants de la fenetre détient le focus.
Gestion dynamique du Look & Feel
    Chaque objet JComponent possède un objet ComponentUI associé qui effectue tous les affichages, la gestion des événements, le calcul des tailles, etc ... La détermination de l'objet ComponentUI est dépendante du Look & Feel courant, qui peut etre fixé en utilisant la méthode UIManager.setLookAndFeel. Consultez la rubrique comment régler le Look & Feel pour plus de détails.
Les propriétés
    Il est possible d'associer une ou plusieurs propriétés (couple nom/objet) à n'importe quel JComponent. Par exemple un gestionnaire d'agencement pourrait utiliser les propriétés pour associer des contraintes aux objets qu'il doit agencer. On régle et récupère les propriétés en invoquant les méthodes putClientProperty et getClientProperty. Pour plus de détails sur les propriétés, reportez vous à Comment utiliser les propriétés.
Support de l'agencement
    Bien que la classe Component fournisse des méthodes facilitant l'agencement, telles que getPreferredSize et getAlignmentX, elle ne fournit d'autre moyens de régler ces propriétés que dhériter et surcharger ces méthodes. Pour avoir un moyen plus simple de régler ses propriétés, la classe JComponent rajoute les méthodes setPreferredSize, setMinimumSize, setMaximumSize, setAlignmentX, et setAlignmentY. Consultez La gestion de l'agencement pour plus d'information.
Support des technologies d'accessibilité
    La classe JComponent fournit une API et les fonctionnalités de base pour aider les technologies d'accessibilité telles que les lecteurs d'écrans, jetez un oeil à Comment gérer le support des technologies d'accessibilité.
Le double buffering
    Le double buffering est une technique permettant d'améliorer la qualité des affichages et de leur mise-à-jour, reportez-vous à Affichage pour plus de détails.
Quelques méthodes permettant d'améliorer l'efficacité de Swing
La classe JComponent possède aussi quelques méthodes plus efficaces que en 1.1. Ces méthodes
JComponent has a few methods that provide more efficient ways to get information than the JDK 1.1 API allowed. The methods include getX and getY, which you can use instead of getLocation; and getWidth and getHeight, which you can use instead of getSize. It also adds one-argument forms of getBounds, getLocation, and getSize for which you specify the object to be modified and returned, letting you avoid unnecessary object creation. These methods have been added to Component for Java 2 (JDK 1.2).

3. L'API JComponent.

    La classe JComponent fournit pleins de nouvelles méthodes et en hérite aussi beaucoup des classes Component et Container. Les tables suivantes résument les méthodes les plus utilisées. Ces tables sont juste une référence, il est préférable de consulter l'API pour obtenir plus de détails.

Adapter l'apparance d'un composant
Méthode  But
void setBorder(Border) 
Border getBorder() 
(in JComponent)
Set or get the border of the component. See How to Use Borders for details.
void setForeground(Color) 
Color getForeground() 
void setBackground(Color) 
Color getBackground()
(in java.awt.Component)
Set or get the foreground or background color for the component. The foreground is generally the color used to draw the text in a component. The background is (not surprisingly) the color of the background areas of the component, assuming that the component is opaque. 
void setOpaque(boolean) 
(in JComponent)
Set whether the component is opaque. An opaque component fills its background with its background color.
boolean isOpaque 
(in JComponent)
Get whether the component is opaque. This method (but not setOpaque) was added to Component in 1.2. 
void setFont(Font) 
Font getFont() 
(in java.awt.Component)
Set or get the component's font. If a font has not been set for the component, the font of its parent is returned.
FontMetrics getFontMetrics(Font) 
(in java.awt.Component)
Get the font metrics for the specified font.


Régler l'état d'un composant
Méthode  But
void setToolTipText(String) 
(in JComponent)
Set the text to display in a tool tip. See How to Use Tool Tips for more information.
void setEnabled(boolean b) 
boolean isEnabled() 
(in java.awt.Component)
Set or get whether the component is enabled. An enabled component can respond to user input and generate events.
void setLocale(Locale l) 
Locale getLocale() 
(in java.awt.Component)
Set or get the component's locale. If the component does not have a locale, the locale of its parent is returned. See Internationalization for information about locales. 
void setCursor(Cursor) 
Cursor getCursor() 
(in java.awt.Component)
Set or get the cursor image to display when the mouse is over the component.
void setVisible(boolean) 
boolean isVisible() 
(in java.awt.Component)
Set or get whether the component is visible. Components are initially visible, with the exception of top-level components. 


La gestion des événements
Méthode  But
void addComponentListener(ComponentListener) 
void removeComponentListener(ComponentListener) 
(in java.awt.Component)
Add or remove a component listener to or from the component. Component listeners are notified when the listened-to component is hidden, shown, moved, or resized.
void addKeyListener(KeyListener) 
void removeKeyListener(KeyListener l) 
(in java.awt.Component)
Add or remove a key listener to or from the component. Key listeners are notified when the user types at the keyboard and the listened-to component has the keyboard focus.
addMouseListener(MouseListener l) 
void removeMouseListener(MouseListener) 
(in java.awt.Component)
Add or remove a mouse listener to or from the component. Mouse listeners are notified when the user uses the mouse to interact with the listened-to component.
void addMouseMotionListener(MouseMotionListener) 
void removeMouseMotionListener(MouseMotionListener) 
(in java.awt.Component)
Add or remove a mouse motion listener to or from the component. Mouse motion listeners are notified when the user moves the mouse within the listened-to component's bounds.
void addContainerListener(ContainerListener) 
void removeContainerListener(ContainerListener) 
(in java.awt.Container)
Add or remove a container listener to or from the container. Container listeners are notified when a component is added to or removed from the listened-to container.
void addFocusListener(FocusListener) 
void removeFocusListener(FocusListener) 
(in java.awt.Component)
Add or remove a focus listener to or from the component. Focus listeners are notified when the listened-to component gains or loses keyboard focus.
Component getNextFocusableComponent() 
void setNextFocusableComponent(Component) 
(in JComponent)
Set or get the next focusable component. null indicates that the focus manager should choose the next focusable component automatically.
void requestFocus() 
boolean hasFocus() 
(in java.awt.Component)
Request that the component get the keyboard focus, or detect whether it has the focus. 
boolean contains(int, int) 
boolean contains(Point p) 
(in java.awt.Component)
Determine whether the specified point is within the component. The argument should be specified in terms of the component's coordinate system. The two int arguments specify x and y coordinates, respectively.
Component getComponentAt(int, int) 
(in java.awt.Container)
Return the component that contains the specified x, y position. The top-most child component is returned in the case where components overlap. This is determined by finding the component closest to the index 0 that claims to contain the given point via Component.contains().


L'affichage des composants
Méthode  But
void repaint() 
void repaint(int, int, int, int) 
(in java.awt.Component)
Request that all or part of the component be repainted. The four int arguments specify the bounds (x, y, width, height, in that order) of the rectangle to be painted. 
void repaint(Rectangle) 
(in JComponent)
Request that the specified area within the component be repainted. 
void revalidate() 
(in JComponent)
Request that the component and its affected containers be laid out again. You shouldn't generally need to invoke this method unless you explicitly change a component's size/alignment hints after it's visible, change a containment hierarchy after it's visible, or perhaps change the data in a component's model directly (without going through the component's API). You might need to invoke repaint after revalidate
void paintComponent(Graphics)
(in JComponent)
Paint the component. Override this method to implement painting for custom components.


Gérer la hiérarchie de conteneurs
Méthode  But
Component add(Component) 
Component add(Component, int) 
void add(Component, Object) 
(in java.awt.Container)
Add the specified component to the container. The one-argument version of this method adds the component to the end of the container. When present, the int argument indicates the new component's position within the container. When present, the Object argument provides layout constraints to the current layout manager.
void remove(int) 
void remove(Component comp) 
void removeAll() 
(in java.awt.Container)
Remove one of or all of the components from the container. When present, the int argument indicates the position within the container of the component to remove. 
JRootPane getRootPane() 
(in JComponent)
Get the root pane ancestor for the component.
Container getParent() 
(in java.awt.Component)
Get the component's parent.
int getComponentCount() 
(in java.awt.Container)
Get the number of components in the container.
Component getComponent(int) 
Component[] getComponents() 
(in java.awt.Container)
Get the one of or all of the components in the container. The int argument indicates the position of the component to get. 


Agencer les composants
Méthode  But
void setPreferredSize(Dimension) 
void setMaximumSize(Dimension) 
void setMinimumSize(Dimension) 
(in JComponent)
Set the component's preferred, maximum, or minimum size, measured in pixels. The preferred size indicates the best size for the component. The component should be no larger than its maximum size and no smaller than its minimum size. Be aware that these are hints only and might be ignored by certain layout managers. 
Dimension getPreferredSize() 
Dimension getMaximumSize() 
Dimension getMinimumSize() 
(in java.awt.Component)
Get the preferred, maximum, or minimum size of the component, measured in pixels. For non-JComponent subclasses, which don't have the corresponding setter methods, you can set a component's preferred, maximum, or minimum size by creating a subclass and overriding these methods. 
void setAlignmentX(float) 
void setAlignmentY(float) 
(in JComponent)
Set the alignment along the x or y axis. These values indicate 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, and 0.5 is centered, and so on. Be aware that these are hints only and might be ignored by certain layout managers. 
float getAlignmentX() 
float getAlignmentY() 
(in java.awt.Component)
Get the preferred, maximum, or minimum size of the component. For non-Swing components, which don't have the corresponding setter methods, you can set a component's preferred, maximum, or minimum size by creating a subclass and overriding these methods. 
void setLayout(LayoutManager) 
LayoutManager getLayout() 
(in java.awt.Container)
Set or get the component's layout manager. The layout manager is responsible for sizing and positioning the components within a container. 


Obtenir les informations de positionnement et de taille
Méthode  But
int getWidth() 
int getHeight() 
(in java.awt.Component)
Get the current width or height of the component measured in pixels.
Dimension getSize() 
Dimension getSize(Dimension) 
(in java.awt.Component)
Get the component's current size measured in pixels. When using the one-argument version of this method, the caller is responsible for creating the Dimension instance in which the result is returned. 
int getX() 
int getY() 
(in java.awt.Component)
Get the current x or y coordinate of the component's origin relative to the parent's upper left corner measured in pixels. 
Rectangle getBounds() 
Rectangle getBounds(Rectangle) 
(in java.awt.Component)
Get the bounds of the component measured in pixels. The bounds specify the component's width, height, and origin relative to its parent. When using the one-argument version of this method, the caller is responsible for creating the Rectangle instance in which the result is returned.
Point getLocation() 
Point getLocation(Point) 
Point getLocationOnScreen() 
(in java.awt.Component)
Gets the current location of the component relative to the parent's upper left corner measured in pixels. When using the one-argument version of getLocation method, the caller is responsible for creating the Point instance in which the result is returned. The getLocationOnScreen method returns the position relative to the upper left corner of the screen.
Insets getInsets() 
(in java.awt.Container)
Get the insets of the component.


Utiliser les positions et les tailles absolus.
Méthode  But
void setLocation(int, int) 
void setLocation(Point) 
(in java.awt.Component)
Set the location of the component, in pixels, relative to the parent's upper left corner. The two int arguments specify x and y, in that order. Use these methods to position a component when you aren't using layout manager.
void setSize(int, int) 
void setSize(Dimension) 
(in java.awt.Component)
Set the size of the component measured in pixels. The two int arguments specify width and height, in that order. Use these methods to size a component when you aren't using layout manager.
void setBounds(int, int, int, int) 
void setBounds(Rectangle) 
(in java.awt.Component)
Set the size and location relative to the parent's upper left corner, in pixels, of the component. The four int arguments specify x, y, width, and height, in that order. Use these methods to position and size a component when you aren't using layout manager.