1. Créer une application Eclipse RCP

Transcription

1. Créer une application Eclipse RCP
ECLIPSE RCP
Modèle d'application
et SWT
Gaël QUEMENER
Ifremer
Février 2014
1/26
Table des matières
1.Créer une application Eclipse RCP................................................................................................................ 2
2. Lier une vue à une classe.......................................................................................................................... 10
2.1 Exemple de code................................................................................................................................. 13
2.2 Event listener....................................................................................................................................... 14
3. GridLayout.................................................................................................................................................. 15
4. Tableau....................................................................................................................................................... 16
4.1 Exemple de création d'un tableau de 128 lignes et 6 colonnes ..........................................................17
4.2 Insertion d'images dans la ligne de titres............................................................................................. 17
4.3 Récupérer la position du curseur de la souris dans le tableau.............................................................18
4.4 Editer un champ dans un tableau........................................................................................................ 20
5.Commands et Handlers............................................................................................................................... 22
6. Références................................................................................................................................................. 25
6.1 Eclipse................................................................................................................................................. 25
6.2 SWT..................................................................................................................................................... 25
1. Créer une application Eclipse RCP
Créer un nouveau projet File->New->Other...
2/26
Figure 1: Création d'un nouveau projet
Choisir un projet de type "Eclipse 4 Application Project" :
3/26
Figure 2: Projet "Eclipse 4 Application Project"
Entrer comme Project Name : myfirstappli. Laisser les options comme dans la figure ci-dessous.
4/26
Figure 3: Nouveau projet plug-in
Cliquer sur "Next".
La page Contents apparait, vérifier que les paramètres sont semblables à ceux de la figure ci-dessous:
5/26
Figure 4: Content
Laisser les paramètres par défaut dans la page e4 Application comme sur la figure ci-dessous:
6/26
Figure 5: Eclipse 4 Application
Cliquer sur "Finish".
Eclipse génère le projet.
7/26
On peut maintenant voir dans le Project explorer l'arborescence du projet :
Figure 6: Représentation du projet dans le Package
Explorer
Double cliquer sur le fichier myfirstappli.product.
On voit apparaitre la vue suivante :
8/26
Figure 7: Edition du fichier .product
Cliquer sur Launch an Eclipse application.
L'application est lancée :
9/26
Figure 8: Première application
2. Lier une vue à une classe
Le but est de créer une classe java qui permettra d'ajouter des éléments graphiques à la vue dans le code.
Dans le Package Explorer, cliquer droit sur le folder myfirstappli/src/myfirstappli et cliquer sur New-Class.
On lui donne le nom SWTPart comme ci-dessous:
10/26
Figure 9: Création d'une nouvelle classe
Cliquer sur Finish, et vérifier que le fichier SWTPart.java a bien été créé.
Retourner sur la page de conficuration de la vue SWT dans Application.e4xmi, cliquer sur le bouton
"Find" à droite du label "Class URI", commencer à taper "swt" dans le champ text. La complétion propose
"myfirstappli.SWTPart", la sélectionner comme ci-dessous, et cliquer sur OK:
11/26
Figure 10: Déclaration de la classe contribuant à une Part
Retournez dans le code de SWTPart.java et faites évoluer le classe de la façon suivante :
package myfirstappli;
import java.awt.BorderLayout;
import javax.inject.Inject;
import
import
import
import
import
org.eclipse.swt.SWT;
org.eclipse.swt.awt.SWT_AWT;
org.eclipse.swt.browser.Browser;
org.eclipse.swt.layout.GridData;
org.eclipse.swt.widgets.Composite;
public class SWTPart {
@Inject
public void init(Composite parent) {
final Browser b = new Browser(parent, SWT.NONE);
b.setUrl("www.youtube.com/");
}
}
Relancez l'application.
12/26
2.1 Exemple de code
Reprenez le code de la méthode SWTPart.init:
@Inject
public void init(Composite parent) {
// creation de la grille
GridLayout layout = new GridLayout(2, false);
parent.setLayout(layout);
// objet texte
final Text text = new Text(parent, SWT.NONE);
text.setText("www.google.com");
GridData data = new GridData(GridData.FILL,
GridData.BEGINNING, true, false, 1, 1);
text.setLayoutData(data);
// objet bouton
Button button = new Button(parent, SWT.NONE);
button.setText("Go To");
data = new GridData(GridData.FILL,
GridData.BEGINNING, false, false, 1, 1);
button.setLayoutData(data);
}
Relancer l'application et regarder le résultat.
Rajoutons le browser :
String httpAddress="www.google.com";
@Inject
13/26
public void init(Composite parent) {
GridLayout layout = new GridLayout(2, false);
parent.setLayout(layout);
final Text text = new Text(parent, SWT.NONE);
text.setText(httpAddress);
GridData data = new GridData(GridData.FILL,
GridData.BEGINNING, true, false, 1, 1);
text.setLayoutData(data);
Button button = new Button(parent, SWT.NONE);
button.setText("Go To");
data = new GridData(GridData.FILL,
GridData.BEGINNING, false, false, 1, 1);
button.setLayoutData(data);
final Browser b = new Browser(parent, SWT.NONE);
b.setUrl(httpAddress);
data = new GridData(GridData.FILL,
GridData.FILL, true, true, 2, 1);
b.setLayoutData(data);
}
2.2 Event listener
Le but est de récupérer un événement graphique.
Dans notre cas, le but est de rafraîchir le browser quand on clique sur le bouton "Go To".
Insérer le code suivant à la fin de la méthode init :
button.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
// Handle the selection event
System.out.println("Button pressed! "+text.getText());
httpAddress=text.getText();
b.setUrl(httpAddress);
}
});
14/26
3. GridLayout
Dans une grille 4x4, le but est de placer des boutons calés horizontalement à gauche, au centre, à droite, et
sur la largeur de la cellule.
On placera des boutons en haut, au centre, en bas, et sur toute la hauteur d'une case.
Illustration 1: exemple GridLayout
Déclarer : GridLayout layout = new GridLayout(4, false);
L'attacher au Composite.
Instancier un bouton.
Lui affecter (button.setLayoutData) un objet GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1)
public GridData(int horizontalAlignment,
int verticalAlignment,
15/26
boolean grabExcessHorizontalSpace,
boolean grabExcessVerticalSpace,
int horizontalSpan,
int verticalSpan)
Constructs a new instance of GridData according to the parameters.
Parameters:
horizontalAlignment - how control will be positioned horizontally within a cell, one of:
SWT.BEGINNING (or SWT.LEFT), SWT.CENTER, SWT.END (or SWT.RIGHT), or SWT.FILL
verticalAlignment - how control will be positioned vertically within a cell, one of:
SWT.BEGINNING (or SWT.TOP), SWT.CENTER, SWT.END (or SWT.BOTTOM), or SWT.FILL
grabExcessHorizontalSpace - whether cell will be made wide enough to fit the remaining
horizontal space
grabExcessVerticalSpace - whether cell will be made high enough to fit the remaining
vertical space
horizontalSpan - the number of column cells that the control will take up
verticalSpan - the number of row cells that the control will take up
4. Tableau
Ajouter une seconde "Part" dans le fichier Application.e4xmi.
Créer une classe pour gérer cette Part.
16/26
4.1 Exemple de création d'un tableau de 128 lignes et 6 colonnes
public class Table1 {
@Inject
public void toto(Composite shell){
Table table = new Table (shell, SWT.MULTI | SWT.BORDER |
SWT.FULL_SELECTION);
table.setLinesVisible (true);
table.setHeaderVisible (true);
GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
data.heightHint = 200;
table.setLayoutData(data);
String[] titles = {"Id", "Titre", "Description", "Auteur", "Répertoire",
"Location"};
for (int i=0; i<titles.length; i++) {
TableColumn column = new TableColumn (table, SWT.NONE);
column.setText (titles [i]);
}
int count = 128;
for (int i=0; i<count; i++) {
TableItem item = new TableItem (table, SWT.NONE);
item.setText (0, "x="+i);
item.setText (1, "blabla");
item.setText (2, "what i want");
item.setText (3, "the one who wrote that data");
item.setText (4, "somewhere");
item.setText (5, "don't know");
}
for (int i=0; i<titles.length; i++) {
table.getColumn (i).pack ();
}
}
}
4.2 Insertion d'images dans la ligne de titres
Utilisation de TableColumn.setImage(Image image);
@Inject
public void init(Composite shell){
Image images[] = new Image[] {
new Image(null, "C:\\Users\\gael\\Desktop\\cours
eclipse\\uml.jpg"),
new Image(null, "C:\\Users\\gael\\Desktop\\cours
eclipse\\uml.jpg"),
new Image(null, "C:\\Users\\gael\\Desktop\\cours
eclipse\\uml.jpg"),
new Image(null, "C:\\Users\\gael\\Desktop\\cours
eclipse\\uml.jpg"),
};
String[] titles = {"Information", "Error", "Question", "Warning"};
String[] questions = {"who?", "what?", "where?", "when?", "why?"};
17/26
shell.setLayout(new GridLayout());
Table table = new Table (shell, SWT.MULTI | SWT.BORDER |
SWT.FULL_SELECTION);
GridData data = new GridData (SWT.FILL, SWT.FILL, true, true);
data.heightHint = 200;
table.setLayoutData (data);
table.setLinesVisible (true);
table.setHeaderVisible (true);
for (int i=0; i<titles.length; i++) {
TableColumn column = new TableColumn (table, SWT.NONE);
column.setText (titles [i]);
column.setImage(images [i]);
}
int count = 128;
for (int i=0; i<count; i++) {
TableItem item = new TableItem (table, SWT.NONE);
item.setText (0, "some info");
item.setText (1, "error #" + i);
item.setText (2, questions [i % questions.length]);
item.setText (3, "look out!");
}
for (int i=0; i<titles.length; i++) {
table.getColumn (i).pack ();
}
}
4.3 Récupérer la position du curseur de la souris dans le tableau
Récupérer le click de la souris par un addListener
Récupérer la zone graphique du tableau par getClientArea
Récupérer la zone de chaque TableItem avec TableItem.getItem(...)
Point size = table.computeSize (SWT.DEFAULT, 200);
table.setSize (size);
table.addListener (SWT.MouseDown, new Listener () {
public void handleEvent (Event event) {
Rectangle clientArea = table.getClientArea ();
Point pt = new Point (event.x, event.y);
int index = table.getTopIndex ();
while (index < table.getItemCount ()) {
boolean visible = false;
TableItem item = table.getItem (index);
for (int i=0; i < 6; i++) {
Rectangle rect = item.getBounds (i);
if (rect.contains (pt)) {
System.out.println ("Item " + index
18/26
+ "-" + i);
table.setSelection(i);
}
if (!visible && rect.intersects
(clientArea)) {
visible = true;
}
}
if (!visible) return;
index++;
}
}
});
19/26
4.4 Editer un champ dans un tableau
Dans un org.eclipse.swt.widgets.Table, déclarer 3 TableColumn.
Instancier les TableItems
Utilisation de la classe org.eclipse.swt.custom.TableEditor
Ajouter un listener au Table de la façon suivante:
shell.setLayout (new FillLayout ());
final Table table = new Table(shell, SWT.BORDER | SWT.MULTI);
table.setLinesVisible (true);
for (int i=0; i<3; i++) {
TableColumn column = new TableColumn (table, SWT.NONE);
column.setWidth(100);
}
for (int i=0; i<3; i++) {
TableItem item = new TableItem (table, SWT.NONE);
item.setText(new String [] {"" + i, "" + i , "" + i});
}
final TableEditor editor = new TableEditor (table);
editor.horizontalAlignment = SWT.LEFT;
editor.grabHorizontal = true;
table.addListener (SWT.MouseDown, new Listener () {
public void handleEvent (Event event) {
Rectangle clientArea = table.getClientArea ();
Point pt = new Point (event.x, event.y);
int index = table.getTopIndex ();
while (index < table.getItemCount ()) {
boolean visible = false;
final TableItem item = table.getItem (index);
for (int i=0; i<table.getColumnCount (); i++) {
Rectangle rect = item.getBounds (i);
if (rect.contains (pt)) {
final int column = i;
final Text text = new Text (table,
SWT.NONE);
Listener textListener = new Listener () {
public void handleEvent (final Event
e) {
switch (e.type) {
case SWT.FocusOut:
item.setText
(column, text.getText ());
text.dispose ();
break;
case SWT.Traverse:
switch (e.detail)
20/26
{
case
SWT.TRAVERSE_RETURN:
item.setText (column, text.getText ());
//FA
LL THROUGH
case
SWT.TRAVERSE_ESCAPE:
text.dispose ();
e.doit = false;
}
break;
}
}
};
text.addListener (SWT.FocusOut,
textListener);
text.addListener (SWT.Traverse,
textListener);
editor.setEditor (text, item, i);
text.setText (item.getText (i));
text.selectAll ();
text.setFocus ();
return;
}
if (!visible && rect.intersects (clientArea)) {
visible = true;
}
}
if (!visible) return;
index++;
}
}
});
21/26
5. Commands et Handlers
Command : déclaration abstraite d'une action (par exemple Save, Open, Quit).
Handler : définit le comportement de la commande (la liaison entre la command et le handler est faite dans
le fichier e4xmi , tag conributionURI).
Définir dans le menu un item "New Tab":
Créer une commande "newTabCommand".
22/26
Créer un handler relié à "newTabCommand"
23/26
Créer une classe java NewTabHandler
package projet01.handlers;
import java.util.List;
import javax.inject.Named;
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
org.eclipse.e4.core.di.annotations.Execute;
org.eclipse.e4.ui.model.application.MApplication;
org.eclipse.e4.ui.model.application.ui.MElementContainer;
org.eclipse.e4.ui.model.application.ui.advanced.MPerspective;
org.eclipse.e4.ui.model.application.ui.advanced.impl.PerspectiveStackImpl;
org.eclipse.e4.ui.model.application.ui.basic.MBasicFactory;
org.eclipse.e4.ui.model.application.ui.basic.MPart;
org.eclipse.e4.ui.model.application.ui.basic.MPartSashContainer;
org.eclipse.e4.ui.model.application.ui.basic.MPartStack;
org.eclipse.e4.ui.model.application.ui.basic.MWindow;
org.eclipse.e4.ui.model.application.ui.basic.MWindowElement;
org.eclipse.e4.ui.services.IServiceConstants;
org.eclipse.e4.ui.workbench.modeling.EModelService;
org.eclipse.jface.dialogs.MessageDialog;
org.eclipse.swt.widgets.Shell;
public class NewTabHandler {
@Execute
public void execute(MApplication application,
EModelService service) {
MPart part = MBasicFactory.INSTANCE.createPart();
part.setLabel("new part");
part.setContributionURI("platform:/plugin/projet01/projet01.newPart");
List<MPartStack> findElements = service.findElements(application,
"mypartstack",MPartStack.class, null);
System.out.println("Found part PartStack(s) : " +
findElements.size());
findElements.get(0).getChildren().add(part);
}
}
24/26
6. Références
6.1 Eclipse
www.eclipse.org
Eclipse 4 RCP wiki:
http://wiki.eclipse.org/Eclipse4/RCP
Eclipse 4 RCP FAQ:
http://wiki.eclipse.org/Eclipse4/RCP/FAQ
Eclipse 4 wiki tutorials
http://wiki.eclipse.org/Eclipse4/Tutorials
Lars Vogel Tutorial :
http://www.vogella.com/articles/EclipseRCP/article.html
Eclipse 4 wiki – Injection de dépendances :
http://wiki.eclipse.org/Eclipse4/RCP/Dependency_Injection
La "bible" Eclipse 4 :
Eclipse 4 RCP: The complete guide to Eclipse application development
Lars Vogel
ISBN-10: 3943747077
ISBN-13: 978-3943747034
http://www.amazon.fr/Eclipse-RCP-complete-application-development/dp/3943747077/
6.2 SWT
Description des widgets:
http://www.eclipse.org/swt/widgets/
Exemples de code SWT :
25/26
http://www.eclipse.org/swt/snippets/
Comprendre les layouts dans SWT :
http://www.eclipse.org/articles/article.php?file=Article-Understanding-Layouts/index.html
Lars Vogel SWT tutorial :
http://www.vogella.com/articles/SWT/article.html
FIN DU DOCUMENT
26/26