cursus de formation aux nouvelles technologies de developpement uv jfc/swing module java expert

117
CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Upload: valentin-sabatier

Post on 03-Apr-2015

105 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT

UV JFC/Swing

Module Java Expert

Page 2: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 2 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Module Java

Vue d’ensemble du langage Java Le langage Java : syntaxe et sémantique Programmation multi-tâche : les threads Accéder aux bases de données Composants réutilisables : le modèle JFC/Swing (MVC) Développement Client/Serveur Présentation d’un IDE : WSAD / Forté / JBuilder Les serveurs d’applications J2EE Les Enterprise JavaBeans Ré-ingénierie d’applications Java

Page 3: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 3 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Introduction aux JFC/Swing

Module Java

Page 4: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 4 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Plan

Introduction Packages Composants Les Evénements Utilisation avancée des Composants

Page 5: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 5 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Qu’est ce que les JFC?

JFC Java Foundation Classes 5 parties :

– Java 1.1 Abstract Window Toolkit (AWT)– Java2D API– ***Swing***– Native Drag and Drop, et Copy and Paste– API pour l'Accessibilité (aveugle, ...)

Page 6: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 6 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Qu’est-ce que Swing?

Abstract Window Toolkit (AWT) V2 100% Pure Java

– Nécessite le JDK 1.1.2 ou supérieur

Fait parti des JFC– Composants– Nouveaux composants de haut niveau– Look & Feel modulable

Page 7: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 7 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Philosophie de l’AWT

Le plus petit dénominateur Commun– Si non disponible en natif sur l’une des plate-formes Java,

alors non disponible sur toutes les plate-formes Java

Ensemble de Composant Simple Composants basés Peer

– La Plate-forme contrôle l’apparence des composants– Inconsistances dans les implémentations

• Interfaçage avec la plate-forme native => erreur

Page 8: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 8 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Ce qui était Mauvais

AWT pas assez efficace Chacun crée de nouveaux Composants

– IFC Netscape– AFC, WFC Microsoft, ...

Temps de chargement de l’Applet trop long– Les éditeurs voulaient leur ensemble de composants,

incorporés dans les browsers

Page 9: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 9 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Philosophie Swing

Ensemble plus Riche de Composants– Remplace l’AWT– Ajoute des composants plus complexes

Composants Swing sont basés sur Java– Si des problèmes, les même problèmes partout

100% Pure Java– Java 1.1.2+ nécessaire– Uniquement le modèle d'événements de Java 1.1

Page 10: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 10 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Les Particularités de Swing

Inclut avec les API Java 2 (JDK 1.2) Utilisable dans les Environnements Java 1.1

– javax.swing.*– Ne peut être dans la hiérarchie java.* et être

téléchargé par des browsers JDK 1.1

Page 11: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 11 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Deux Vues des Swing

Alternative aux composants AWT Java 1.1– modèle d’événements 1.0 NON supporté– Quelques nouveaux composants.

Interface Model/View/Controller– Séparer les données des vues écrans et des interactions– Plus de travail nécessaire

Page 12: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 12 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

L’ensemble des composants Swing

Exemple de programme basé sur les Swing

Page 13: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 13 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

De l’AWT aux SWING

Pour la plupart des composants, ajouter J avant le nom– Button JButton, Applet JApplet, …

Modèle d'événements Java 1.1 Les containers Swing intègrent le double-buffer

– Evite le scintillement des composants Swing

Page 14: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 14 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Swing : le remplacement de l’AWT

Module Java

Page 15: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 15 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Le Look and Feel

Personnaliser l ’aspect des composants graphiques :– indépendant des plate-formes : style Metal– dépendant du système :windows, ...

Page 16: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 16 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Le Look and Feel

Page 17: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 17 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Le Look and Feel

Utiliser le look d ’affichage Metal

try { UIManager.setLookAndFeel (

"javax.swing.plaf.metal.MetalLookAndFeel");} catch (java.lang.ClassNotFoundException e) { // Ne peut changer le look and feel}

Page 18: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 18 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Le Look and Feel

Utiliser le look d ’affichage Metal

try { UIManager.setLookAndFeel (

UIManager.getCrossPlatformLookAndFeelClassName());} catch (java.lang.ClassNotFoundException e) { // Ne peut changer le look and feel}

Page 19: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 19 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Le Look and Feel

Utiliser le look d ’affichage du système

try { UIManager.setLookAndFeel (

UIManager.getSystemLookAndFeelClassName());} catch (java.lang.ClassNotFoundException e) { // Ne peut changer le look and feel}

Page 20: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 20 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Swing vs. AWT 1.1

class MyActionListener implements ActionListener { public void actionPerformed (ActionEvent e) { System.out.println (e.getActionCommand()); }}...ActionListener al = new MyActionListener();Button b1 = new Button ("Hello");b1.addActionListener (al);add (b1, BorderLayout.NORTH);

JButton b2 = new JButton ("World");b2.addActionListener (al);add (b2, BorderLayout.SOUTH);

Page 21: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 21 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Les JButton Swing

import java.awt.*; import javax.swing.*;public class MyFrame1 extends Frame { Icon icon1 = new ImageIcon ("space01.jpg"); Icon icon2 = new ImageIcon ("space02.jpg"); Icon icon3 = new ImageIcon ("space03.jpg"); public MyFrame1() { JButton b1 = new JButton (icon1); b1.setPressedIcon (icon2); b1.setRolloverIcon (icon3); b1.setRolloverEnabled (true); b1.setToolTipText ("Hello"); add (b1, BorderLayout.NORTH); } public static void main (String args[]) { Frame f = new MyFrame1(); f.pack(); f.show(); }}

Page 22: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 22 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Amélioration des JButton

Support des composants Image– Actuellement supporte les “Icon”– MediaTracker non nécessaires – Serializable

Séparer les Icons des différents états– Normal / Disabled / Disabled-Selected / Pressed / Rollover /

Selected

Texte d’aide : ToolTip Raccourcis clavier

Page 23: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 23 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Vue des composants Swing

Module Java

Page 24: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 24 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Vue des paquetages Swing

La collection Swing est constitué de 17 paquetages

javax.swing – le paquetage Swing racine définit les composants, les

adapters, les modèles par défaut des composants, et les interfaces pour tous les modèles et les containers.

Page 25: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 25 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Vue des paquetages Swing

javax.swing.border – Le paquetage border déclare l ’interface Border et ses classes, afin

de définir les styles d ’affichage spécifiques aux bords des composants.

javax.swing.colorchooser – Le paquetage colorchooser contient les classes pour choisir la

couleur du composant.

Page 26: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 26 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Vue des paquetages Swing

javax.swing.event – Le paquetage event est pour les types d ’événements et les

listeners spécifiques des composants Swing. En plus des types java.awt.event, les composants Swing peuvent générer leurs propres types d ’événements.

javax.swing.filechooser – le paquetage filechooser contient les classes pour la sélection de

fichiers.

Page 27: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 27 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Vue des paquetages Swing

javax.swing.plaf.* – Le paquetage look-and-feel (Pluggable Look And Feel) contient

les classes (delegates) de l ’Interface Utilisateur (UI) qui implémentent les aspects des composants Swing. javax.swing.table

– Le paquetage table définit les interfaces et les classes pour les tableaux.

Page 28: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 28 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Vue des paquetages Swing

javax.swing.text – Le paquetage text contient les classes pour le framework des

documents Swing.

javax.swing.text.html.* – Le paquetage text.html contient les classes pour l ’analyse et

l ’affichage de l ’HTML version 3.2.

Page 29: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 29 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Vue des paquetages Swing

javax.swing.text.rtf – Le paquetage text.rtf définit les classes pour le rendu de

documents basic Rich Text Format (RTF).

javax.swing.tree – Le paquetage tree contient les interfaces et les classes qui

supportent l ’affichage sous forme d ’arbres (explorateur Window).

Page 30: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 30 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Vue des paquetages Swing

javax.swing.undo – Le paquetage undo permet le support des classes pour

implémenter les capacités du undo/redo dans une GUI.

javax.accessibility – Le paquetage JFC Accessibility est inclu avec les classes

Swing, pour le support d ’outils d ’aide aux personnes handicapées.

Page 31: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 31 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Hiérarchie Swing

Page 32: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 32 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Hiérarchie Swing

Page 33: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 33 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Les Icônes

Une image de taille fixe Peuvent être utilisées avec la plupart des composants

(e.g. JButton) Icon est une interface que n’importe quelle classe peut

implémenter Icon utilisé à la place de Image car Image est chargé

de manière asynchrone et non sérialisable

Page 34: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 34 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Exemple de création d ’Icône

ImageIcon image1 = new ImageIcon(’’bouton1.gif’’);

ImageIcon image2 = new ImageIcon(’’bouton2.gif’’);

Page 35: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 35 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Utilisation des composants Swing

Module Java

Page 36: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 36 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Composants de haut niveau

Toutes les sous-classes de Window, non de JComponent Non portables, ils ont des composants peer Composants ajoutés au panel de contenu

– interface RootPaneContainer - délégué au container

Page 37: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 37 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Utilisation du RootPaneContainer

Ne pas ajouter de composants directement dans les containers de haut niveau :– aFrame.add (new Button (“Help”));

Ajouter au panel de contenu:“content pane”– aJFrame.getContentPane().add (…);– possède un Layout manager - par défaut: BorderLayout

JDialog, JFrame, JWindow, JApplet, JInternalFrame

Page 38: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 38 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Exemple de JFrame

public class FrameTester { public static void main (String args[]) { JFrame f = new JFrame ("JFrame Example"); Container c = f.getContentPane(); c.setLayout (new FlowLayout()); for (int i = 0; i < 5; i++) { c.add (new JButton ("No")); c.add (new Button ("Batter")); } c.add (new JLabel ("Swing")); f.setSize (300, 200); f.show(); }}

Page 39: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 39 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Comportement de fermeture d’une JFrame

Lorsque l’utilisateur sélectionne l’option de fermeture de la fenêtre Jframe => comportement par défaut– Frame ne fait rien– JFrame est caché (mais non détruite)

setDefaultCloseOperation (opération)– JFrame.DO_NOTHING_ON_CLOSE– JFrame.HIDE_ON_CLOSE– JFrame.DISPOSE_ON_CLOSE– JFrame.EXIT_ON_CLOSE

Page 40: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 40 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

JApplet

L’utilisation de composants Swing dans une applet nécessite d’utiliser la sous-classe JApplet, et non Applet– JApplet est une sous-classe de Applet– Peut avoir une JMenuBar– LayoutManager par défaut est BorderLayout

Page 41: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 41 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

JOptionPane

Boîtes de dialogues standard– Yes, No, Cancel - ou paramétrables– Message d’avertissement, une question– Saisies utilisateurs– Les boîtes de dialogues bloquent le thread courant– String response =

JOptionPane.showInputDialog(this, "Enter input:");

Page 42: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 42 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

4 types de JOptionPane

ConfirmDialog– pose une question, avec des boutons réponses : Yes, No et

Cancel

InputDialog– Invite à saisir du texte

MessageDialog– affiche un message

OptionDialog– inclut les 3 autres types de boîtes

Page 43: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 43 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Exemples de JOptionPane

Page 44: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 44 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Pour créer une boîte de dialogue :– showConfirmDialog(Composant, Objet)– Composant est le conteneur à considérer comme le parent de la boîte

de dialogue (null autorisé)– Objet est soit une chaîne, un composant ou une icône (à la place du

message)

Le composant ConfirmDialog

Page 45: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 45 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Pour créer une boîte de dialogue :– showConfirmDialog(Composant, Objet, Titre, BoutonsOption,

TypeBoite)– BoutonsOption pour configurer les types de boutons– TypeBoite pour spécifier le type de message à afficher

Le composant ConfirmDialog

Page 46: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 46 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

La ConfirmDialog Retourne – JOptionPane.YES_OPTION, – JOptionPane.NO_OPTION – JOptionPane.CANCEL_OPTION

Le composant ConfirmDialog

Page 47: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 47 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Le paramètre TypeBoite spécifie l’icône– JOptionPane.ERROR_MESSAGE– JOptionPane.INFORMATION_MESSAGE– JOptionPane.PLAIN_MESSAGE– JOptionPane.QUESTION_MESSAGE– JOptionPane.WARNING_MESSAGE

Le composant ConfirmDialog

Page 48: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 48 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Exemple de ConfirmDialog

int reponse;

reponse = JOptionPane.showConfirmDialog(null, ’’Voulez-vous… ?’’);

Page 49: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 49 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Exemple de ConfirmDialog

int reponse;

reponse = JOptionPane.showConfirmDialog(null, ’’Voulez-vous… ?’’,

’’ Titre Question’’,

JOptionPane.YES_NO_OPTION,

JOptionPane.ERROR_MESSAGE);

Page 50: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 50 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Pour créer une boîte de dialogue d ’entrée de texte :– showInputDialog(Composant, Objet)– showInputDialog(Composant, Objet, Titre, TypeBoite)

Le composant InputDialog

Page 51: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 51 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

La InputDialog Retourne – String

Paramétrage de la InputDialog :– JOptionPane.ERROR_MESSAGE– JOptionPane.INFORMATION_MESSAGE– JOptionPane.PLAIN_MESSAGE– JOptionPane.QUESTION_MESSAGE– JOptionPane.WARNING_MESSAGE

Le composant InputDialog

Page 52: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 52 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Exemple de InputDialog

String reponse;

reponse = JOptionPane.showInputDialog(null, ’’Saisir … ?’’);

Page 53: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 53 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Exemple de InputDialog

String reponse;

reponse = JOptionPane.showInputDialog(null, ’’Saisir … ?’’,

’’ Boite Saisie ’’, JOptionPane.QUESTION_MESSAGE);

Page 54: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 54 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Pour créer une boîte de message :– showMessageDialog(Composant, Objet)– showMessageDialog(Composant, Objet, Titre, TypeBoite)

Le composant MessageDialog

Page 55: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 55 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

La MessageDialog Retourne – PAS DE VALEUR DE RETOUR

Paramétrage de la MessageDialog :– JOptionPane.ERROR_MESSAGE– JOptionPane.INFORMATION_MESSAGE– JOptionPane.PLAIN_MESSAGE– JOptionPane.QUESTION_MESSAGE– JOptionPane.WARNING_MESSAGE

Le composant MessageDialog

Page 56: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 56 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Exemple de MessageDialog

JOptionPane.showMessageDialog(null, ’’Attention … !?’’);

Page 57: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 57 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Exemple de MessageDialog

JOptionPane.showMessageDialog(null, ’’Attention … !?’’,

’’ Avertissement ’’,

JOptionPane.WARNING_MESSAGE);

Page 58: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 58 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Pour créer une boîte de dialogue entièrement paramétrable :– showOptionDialog(Composant, Objet,

Titre,

BoutonsOption,

TypeBoite,

IconTypeBoite,

Object[], ObjetDefaut)

Le composant OptionDialog

Page 59: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 59 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

La OptionDialog Retourne – JOptionPane.YES_OPTION, – JOptionPane.NO_OPTION – JOptionPane.CANCEL_OPTION– le numéro du bouton sélectionné

Le composant OptionDialog

Page 60: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 60 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Le paramètre BoutonsOption – JOptionPane.YES_NO_CANCEL_OPTION, – JOptionPane.YES_NO_OPTION – 0 pour spécifier des boutons spécifiques

Le composant OptionDialog

Page 61: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 61 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Le paramètre TypeBoite spécifie l’icône– JOptionPane.ERROR_MESSAGE– JOptionPane.INFORMATION_MESSAGE– JOptionPane.PLAIN_MESSAGE– JOptionPane.QUESTION_MESSAGE– JOptionPane.WARNING_MESSAGE

Le composant OptionDialog

Page 62: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 62 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Exemple de OptionDialog

JButton[] genre = new JButton[3];

genre[0] = new JButton(’’ Homme’’);

genre[1] = new JButton(’’ Femme’’);

JOptionPane.showOptionDialog(null, ’’Genre Humain’’,

’’Sexe’’, // titre

0, // Boutons spécifiques

JOptionPane.INFORMATION_MESSAGE,

null, // pas d ’icône spécifique

genre, // liste des boutons

genre[1]); // le bouton défaut

Page 63: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 63 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Remplacements de l’AWT

JLabel - comme Label– Simple ligne de texte– supporte également Icon, Border, – Position du text/icon dans 9 zones, vs. 3 alignements

JButton - comme Button– Simple libellé de texte– Supporte Icon, positionnement, ...

Page 64: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 64 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Les JLabels

JLabel fancyLabel = new JLabel("Fancy Big Label");

// Instantiate a Font object to use for the label

Font fancyFont = new Font("Serif", Font.BOLD | Font.ITALIC, 32);

// Associate the font with the label

fancyLabel.setFont(fancyFont);

// Create an Icon

Icon tigerIcon = new ImageIcon("SmallTiger.gif");

// Place the Icon in the label

fancyLabel.setIcon(tigerIcon);

// Align the text to the right of the Icon

fancyLabel.setHorizontalAlignment(JLabel.RIGHT);

Page 65: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 65 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Les JButton

Icon tigerIcon = new ImageIcon("SmallTiger.gif"); JButton myButton = new

JButton("Tiger", tigerIcon); add(myButton);

Page 66: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 66 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Remplacements de l’AWT /2

JPanel - comme Panel– Double-buffer (pas comme JCanvas)

JCheckBox - commeCheckbox: case à cocher– choix Oui-Non, ou les états On-Off

JRadioButton :case à cocher (cercle)– groupé avec ButtonGroup, pas CheckboxGroup

JToggleButton - pas d’équivalent AWT– Offre un état “stay pressed”

– A utiliser pour les barres d’outils

– Sous classes directes : JCheckBox, JRadioButton

Page 67: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 67 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Les JPanels

Les JPanels permettent d ’afficher toutes sortes d ’éléments graphiques.

Ils disposent d ’une surface d ’affichage Graphics, permettant de dessiner les composants à l ’aide de paintComponent()

Ils fonctionnent souvent de manière autonomes (Threads), pour obtenir un affichage régulier.

Page 68: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 68 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Création d ’un JPanel

Class monPanel extends JPanel

{ // constructeur

monPanel()

{}

// affichage des composants graphiques

public void paintComponent(Graphics g)

{ Graphics2D g2d = (Graphics2D) g;

g.drawString(’’hello’’);

}

}

Page 69: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 69 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Création d ’un JPanel autonome

Class monPanel extends JPanel implements Runnable

{ Tread panel; //thread chargé de l ’affichage du panel

// constructeur

monPanel()

{ panel = new Thread(this); //création du thread

panel.start(); //lancement du thread

}

public void paintComponent(){//…

}

public void run()

{ while(true)

{ repaint(); / demander le ré-affichage

}

}

}

Page 70: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 70 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Exemple de JCheckBox

public class CheckboxPanel extends JPanel { Icon unchecked = new ToggleIcon (false); Icon checked = new ToggleIcon (true); public CheckboxPanel() { // Set the layout for the JPanel

setLayout(new GridLayout(2, 1)); // initialized to true JCheckBox cb1 = new JCheckBox("Choose Me", true); cb1.setIcon(unchecked); cb1.setSelectedIcon(checked); // initialized to false JCheckBox cb2 = new JCheckBox( "No Choose Me", false); cb2.setIcon(unchecked); cb2.setSelectedIcon(checked); add(cb1);add(cb2); }

Page 71: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 71 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Exemple de JCheckBox

class ToggleIcon implements Icon { boolean state; public ToggleIcon (boolean s) { state = s; } public void paintIcon (Component c, Graphics g, int x, int y) { int width = getIconWidth();

int height = getIconHeight(); g.setColor (Color.black); if (state)

g.fillRect (x, y, width, height); else g.drawRect (x, y, width, height);

} public int getIconWidth() { return 10; } public int getIconHeight() { return 10; } } }

Page 72: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 72 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Remplacements de l’AWT : JRadioButton

JRadioButton et ButtonGroupJRadioButton radioButton; ButtonGroup rbg = new ButtonGroup(); JLabel label = new JLabel("Annual Salary: "); radioButton = new JRadioButton("$45,000");add(radioButton);rbg.add (radioButton); radioButton.setSelected(true); radioButton = new JRadioButton("$60,000"); add(radioButton);rbg.add (radioButton); radioButton = new JRadioButton("$75,000"); add(radioButton);rbg.add (radioButton);

Page 73: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 73 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Remplacements de l’AWT : JToggleButton

JToggleButton:JToggleButton feetToggle = new JToggleButton();

feetToggle.setSelected(true);

feetToggle.setText("feetToggleButton.label");

feetToggle.setToolTipText("feetToggleButton.tooltip");

feetToggle.addChangeListener(new ChangeListener() {

public void stateChanged(ChangeEvent event)

{ if (feetToggle.isSelected())

{ // actions

}

}});

Page 74: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 74 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Remplacements de AWT : JComboBox

JComboBox - Comme Choice– liste modifiable : éditable - setEditable(true)

– Auto-initialiser suivant la taille de la liste• JComboBox jc = new JComboBox (ObjectArray);

– Ajouter un élément : addItem(Objet)

– Récupérer un élément : getItemAt(int indice)

– connaître le nombre d’éléments : getItemCount()

– Récupérer la position d’un élément sélectionné : getSelectedIndex()

– Récupérer le texte de l’élément sélectionné : getSelectedItem()

Page 75: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 75 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

JComboBox

Modèle de données - ComboBoxModel– hérite de ListModel

– get/setSelectedItem

Vue - ListCellRenderer– getListCellRendererComponent()

Page 76: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 76 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Remplacements de AWT : JList

JList - like List– Auto-initialise à partir d’un tableau ou d’un vecteur

• setListData(Tableau), setListData(Vecteur)

– Défillement non supporté• Doit être mise dans un JScrollPane

JList dataList = new JList(vecteur);

JScrollPane scrollPane = new JScrollPane(dataList);

– Supporte la séléction simple ou multiple

String[] data = {"one", "two", "free", "four"}; JList dataList = new JList(data); dataList.setSelectedIndex(1); dataList.getSelectedValue(); // returns "two"

Page 77: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 77 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Remplacements de AWT : JList

JList : quelques méthodes pratiques– Retourner l’indice(s) du (des) premier(s) élément(s) sélectionné(s):

getSelectedIndex() ou getSelectedIndices()

– Retourner l’objet(s) du (des) premier(s) élément(s) sélectionné(s): getSelectedValue() ou getSelectedValues()

– spécifier une sélection multiple :• setSelectionMode(int selectionMode)

– ListSelectionModel.SINGLE_SELECTION

– ListSelectionModel.SINGLE_INTERVAL_SELECTION

– ListSelectionModel.MULTIPLE_INTERVAL_SELECTION

Page 78: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 78 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Remplacements de AWT : JList

final JList list = new JList(dataModel);

MouseListener mouseListener = new MouseAdapter()

{ public void mouseClicked(MouseEvent e)

{ if (e.getClickCount() == 2)

{ int index = list.locationToIndex(e.getPoint()); System.out.println("Double click sur l ’Item " + index);

}

}

};

list.addMouseListener(mouseListener);

Page 79: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 79 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Remplacements de AWT : JList

DefaultListModel model = new DefaultListModel();

JList statusList = new JList(model);

// modifier la liste des items

model.addElement("test line one");

model.addElement("foo foo foo");

model.addElement("quick brown fox");

Page 80: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 80 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Les JList

Plus seulement du texte peut afficher des Icônes peut modifier l’affichage d’une ligne lorsqu’elle est

sélectionnée Modèle de données- ListModel

– defaut: DefaultListModel

– getSize / getElementAt (position)

Vue - ListCellRenderer– getListCellRendererComponent()

Page 81: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 81 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Remplacements de AWT : JScrollPane

JScrollPane - comme ScrollPane– Défilement de composants

• donnés dans le constructeur

• délégués au Container– Ajouté au viewport par getViewPort().add()

– Peut placer des objets dans l’un des quatre coins internes (entêtes des colonnes ou entêtes de lignes)

• Les Tables utilisent automatiquement la zone d'en-tête colonne

Page 82: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 82 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Le ViewPort

Permet de faire scroller

soi-même les barres de

défilement

Page 83: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 83 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Remplacements de AWT: JScrollPane

Initialiser un JScrollPane– JScrollPane(Composant)– JScrollPane(Composant, barreVerticale, barreHorizontale)– les barres sont des entiers (exemple vertical):

• ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS

• ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED

• ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER

Page 84: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 84 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Remplacements de AWT JScrollPane

Exemple de JScrollPane

JPanel panel = new JPanel();

JTextArea lettre = new JTextArea(5,15);

JScrollPane scroll = new JScrollPane(lettre,

ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,

ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER,

);

panel.add(scroll); //afficher la lettre dans le panel

setContentPane(panel); // associer le panel à une Jframe

setLayout(new BorderLayout());

Icon bigTiger = new ImageIcon("BigTiger.gif");

JLabel tigerLabel = new JLabel(bigTiger);

JScrollPane scrollPane = new JScrollPane(tigerLabel);

add(scrollPane, BorderLayout.CENTER);

Page 85: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 85 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

La JTable

Peut créer une JTable à partir d’un tableau[][] et des noms de colonnes[]

Modèle de données - TableDataModel – defaut: DefaultTableModel

– getRowCount, getValueAt, setValueAt, getColumnCount, getColumnName, ...

Vue - JTable– Contient JTableColumns

Page 86: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 86 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Les JTable

public class TablePanel extends JPanel { TablePanel()

{ setLayout (new BorderLayout());

// Créer le modèle de donnéesEmployeeDataModel employeeModel = new EmployeeDataModel();

// Créer/initialiser la table JTable table = new JTable (employeeModel);

// Placer la table dans un JScrollPane JScrollPane scrollPane = new JScrollPane (table); // Ajouter à l ’écranadd(scrollPane, BorderLayout.CENTER);

} }

Page 87: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 87 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Les JTable

class EmployeeDataModel extends AbstractTableModel { // hériter de AbstractTableModel, au lieu d’implémenter TableModel soi-même,

// AbstractTableModel s ’occupe de la gestion de la liste TableModelListenerString columns[] = {"Employee ID", "First Name", "Last Name", "Department"}; String rows[][] = { {"0181", "Bill", "Cat", "Political Candidate"}, {"0915", "Opus", "Penguin", "Lost and Found"}, {"1912", "Milo", "Bloom", "Reporter"}, {"3182", "Steve", "Dallas", "Legal"}, {"4104", "Hodge", "Podge", "Style"}, {"5476", "Billy", "Boinger", "Entertainment"}, {"6289", "Oliver", "Jones", "Science"}, {"7268", "Cutter", "John", "Travel"} ,

{"8133", "W. A.", "Thornhump", "C.E.O"}, {"9923", "Berke", "Breathed", "Editor"} }

};

Page 88: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 88 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Les JTable

private int numColumns = columns.length; private int numRows = rows.length;

public int getColumnCount() { return numColumns; }

public int getRowCount() { return numRows; }

public Object getValueAt (int row, int column) { return rows[row][column]; }

public String getColumnName (int columnIndex) { return columns[columnIndex]; }

Page 89: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 89 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Les JTable

public void setValueAt (Object aValue, int row, int column) { String cellValue;

if (aValue instanceof String) cellValue = (String)aValue;

else cellValue = aValue.toString();

rows[row][column] = cellValue; fireTableCellUpdated (row, column);

} public boolean isCellEditable(int row, int column)

{ // first column is read-only return (column != 0); }

}

Page 90: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 90 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Exemple de JTable

Page 91: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 91 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Remplacements du texte AWT

JTextComponent est le composant parent de tous les composants textes :– Un modèle séparé connu sous le nom de document, pour gérer le

contenu du document.

– Une vue séparée, en charge de l ’affichage du composant à l ’écran.

– Un controller séparé, connu sous le nom editor kit, qui permet de lire et écrire du texte et qui implémente les capacités d ’édition avec des actions (ActionListener)

Page 92: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 92 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Le JTextComponent

Quelques méthodes communes :

– copy() copie la selection courante de texte dans le presse-papier

– cut() coupe la selection courante de texte dans le presse-papier

– paste() colle le contenu du presse-papier dans le document

– getSelectedText() retourne la selection de texte contenu dans le document

Page 93: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 93 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Le JTextComponent

– setSelectionStart(int) mettre le point de départ de la selection à la position passé en paramètre

– setSelectionEnd(int) mettre le point de fin de la selection à la position passé en paramètre

– selectAll() sélectionne tout le texte dans le document

– replaceSelection(String) remplace la selection courante par le texte en paramètre

Page 94: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 94 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Le JTextComponent

– getText() retourne le texte contenu dans le composant

– setText(String) mettre du texte dans le document

– setEditable(boolean) indique si le document est éditable

Page 95: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 95 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Remplacements du texte AWT

JTextField - comme TextField– Supporte la justification du text– JPasswordField pour les passwords

JTextArea - commeTextArea

Page 96: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 96 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Remplacements du texte AWT

JEditorPane - éditeur/viewer portable pour l’HTML/RTF JTextPane - supporte le texte stylisé

– Créer un DefaultStyledDocument pour les données

DefaultStyledDocument doc = new DefaultStyledDocument();

– Créer un JTextPane utilisant le modèle.

JTextPane pane = new JTextPane (doc);

– Placer le JTextPane dans un JScrollPane

JScrollPane scrollPane = new JScrollPane(pane);

Page 97: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 97 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Remplacements du texte AWT

JTextPane - attributs du document– static final String NORMAL = "Normal";

– static final String ITALIC = "Italic";

– static final String BIG = "Big";

Page 98: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 98 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Remplacements du texte AWT

JTextPane - attributs du document// Stocker l ’ensemble des styles;

paraStyles = new Hashtable();

SimpleAttributeSet attr = new SimpleAttributeSet();

paraStyles.put(NORMAL, attr);

attr = new SimpleAttributeSet();

StyleConstants.setItalic(attr, true);

paraStyles.put(ITALIC, attr);

attr = new SimpleAttributeSet();

StyleConstants.setFontSize(attr, 36);

paraStyles.put(BIG, attr);

Page 99: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 99 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Remplacements du texte AWT

JTextPane - attributs du document// effacer le document courantpane.setStyledDocument(doc = new DefaultStyledDocument());// Prendre le style NORMALAttributeSet defaultStyle = (AttributeSet) paraStyles.get(NORMAL);// Prendre le style ITALICAttributeSet italicStyle = (AttributeSet) paraStyles.get(ITALIC);// Prendre le style BIGAttributeSet bigStyle = (AttributeSet) paraStyles.get(BIG);// Insérer du texte dans le documentdoc.insertString(doc.getLength(), "Hello World\n", bigStyle);doc.insertString(doc.getLength(), "What's up Doc?\n", italicStyle);doc.insertString(doc.getLength(), "Boring...\n", defaultStyle);

Page 100: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 100 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Remplacements du texte AWT

Page 101: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 101 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Remplacements des ScrollBar

JScrollBar - comme Scrollbar JSlider - Scrollbar pour la sélection de valeurs

– Associer des labels aux cotations

Page 102: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 102 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

JSlider Example

JSlider right, bottom;

right = new JSlider(JSlider.VERTICAL, 1, 9, 3);

Hashtable h = new Hashtable();

h.put (new Integer (1), new JLabel("Mercury"));

h.put (new Integer (2), new JLabel("Venus"));

...

h.put (new Integer (9), new JLabel("Pluto"));

right.setLabelTable (h);

right.setPaintLabels (true);

right.setInverted (true);

bottom = new JSlider(JSlider.HORIZONTAL, 0, 100, 25);

bottom.setMajorTickSpacing (10);

bottom.setPaintLabels (true);

Page 103: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 103 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Les barres de Progression

Affiche la progression d’une opération– Peut être utilisé comme une jauge

Initialisation de la barre de progression– JProgressBar()– JProgressBar(valMin, valMax)– JProgressBar(valMin, valMax, orientation)– L’orientation peut être:

• SwingConstants.VERTICAL• SwingConstants.HORIZONTAL

Page 104: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 104 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Les barres de Progression

Utilisation:– Initialiser

JProgressBar progressBar = new JProgressBar();progressBar.setMinimum(0);progressBar.setMaximum(nombreOperations);

– LancerprogressBar.setValue(progressBar.getMinimum());for (int i = 0; i < numberSubOperations; i++) { progressBar.setValue(i); executerOperation(i);}

– L’affichage du taux de progression est réalisé par la méthode setStringPainted(true)

Page 105: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 105 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Tool tips

Chaîne de texte dépendant du contexte qui s’affiche lorsque la souris est présente au dessus d’un objet

La classe JToolTip le supporte– rarement utilisé– Utilise la méthode setToolTipText de JComponent

ToolTipManager gère les bulles d’informations

Page 106: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 106 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Les barres d’outils

Affiche les composants enligne/colonne

peut être flottante ou accrochée Peut contenir n’importe quel composant

– Mieux si identique, ou similaire– Utiliser les JToggleButton

Possède la méthode addSeparator

Page 107: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 107 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Les Panneaux à Onglets

Les panneaux à onglets permettent de gérer et d’accéder à de multiples panels d’affichage

Les onglets sont ajoutés en utilisant – addTab(TexteOnglet, Icone, Composant)– addTab(TexteOnglet, Composant)

Page 108: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 108 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Les Panneaux à Onglets

public class TabbedPanel extends JPanel { String tabs[] = {"One", "Two", "Three", "Four"}; public JTabbedPane tabbedPane = new JTabbedPane(); public TabbedPanel() { setLayout (new BorderLayout()); for (int i=0;i<tabs.length;i++) tabbedPane.addTab (tabs[i], null, createPane (tabs[i])); tabbedPane.setSelectedIndex(0); add (tabbedPane, BorderLayout.CENTER); } JPanel createPane(String s) { JPanel p = new JPanel(); p.add(new JLabel(s)); return p; }}

Page 109: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 109 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Quelques événements Swing

Module Java

Page 110: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 110 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Swing Events

Page 111: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 111 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Les Evénements

Les classes Listener pour le support de chaque type d’événements

Chaque événement possède une source Swing (composant)

Héritent des événements des Composants / Container 1.1

Page 112: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 112 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Les événements Actions

L’interface Action hérite de ActionListener– lorsque des contrôles multiples sont nécessaires– classe AbstractAction implémente Action

• gère la liste des contrôles et des actions

– Ajouts d’Actions supportés par les JMenu, JPopupMenu, et les JToolBar

Page 113: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 113 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Les Actions

Il est possible d’ajouter une Action une barre d’outil La barre d’outils crée un bouton et demande l’Action

que l’icône invoque Facilite la séparation entre le comportement et l’UI

– faciliter de programmation de l’interface

Page 114: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 114 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Implémentation des Actions

Définition d’une Actionclass CutAction extends AbstractAction { public CutAction () { super (“Cut”, new ImageIcon(“Scissors.gif”); } public void actionPerformed (ActionEvent e) { System.out.println ("Selected: " + getValue (Action.NAME)); }}

Insérer à différents endroits (Action a = new MyAction(...);)

– aJMenu.add (a) / aJToolBar.add (a) / …

Page 115: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 115 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Les Actions Text

TextAction hérite de AbstractAction demande au composant texte comment gérer une

opération– Action actions[] = aJTextComp.getActions();

Trouve l’Action pour exécuter une opération– recherche à travers un tableau

Associer une Action à un composant– addActionListener(...)

Page 116: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 116 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

Les Actions Text

Récupérer la liste des ActionsHashtable commands = new Hashtable();

Action[] actions = jt.getActions();

for (int i = 0; i < actions.length; i++) {

Action a = actions[i];

commands.put(a.getValue(Action.NAME), a);

}

Trouver une action / un composantJButton cut = new JButton("Cut");

Action cutIt = (Action)commands.get (DefaultEditorKit.cutAction);

cut.addActionListener (cutIt);

Page 117: CURSUS DE FORMATION AUX NOUVELLES TECHNOLOGIES DE DEVELOPPEMENT UV JFC/Swing Module Java Expert

Module UV JavaPage 117 / 117

Deruelle LaurentCopyright © 2002 Laurent Deruelle

L’appui de touches

KeyStroke représente une touche clavierKeyStroke stroke = KeyStroke.getKeyStroke (KeyEvent.VK_J, ActionEvent.ALT_MASK, true); //

ALT-J

Associé à un JComponentjb.registerKeyboardAction (new MyActionListener(), stroke, JComponent.WHEN_FOCUSED);

Lorsque l’appui de la touche survient, l’action est déclenchée– Conditions: WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW,

WHEN_ANCESTOR_OF_FOCUSED_COMPONENT