SlideShare ist ein Scribd-Unternehmen logo
1 von 37
Downloaden Sie, um offline zu lesen
Créer des interfaces utilisateurs avec Java
                      et Swing




                                              1
Premier exemple.




Nous utilisons ici les composants les plus communs d'une interface.

Leur traduction en Swing :
- Une fenêtre principale (avec boutons d'agrandissement, réduction, fermeture…) : JFrame
- Un plan rectangulaire : JPanel
- Un bouton : Jbutton
- Une zone texte : Jlabel




                                                                                           2
Le modèle par Container
La JFrame est un composant qui contient tous les autres.
Le JPanel est un container intermédiaire qui va se charger de contenir le label et le bouton.

Le JButton et le JLabel sont des composants atomiques.
Autres exemples : zone de texte éditable (JTextField), table (JTable), etc…


Diagramme de hiérarchie (contenance) – arborescence :




Remarque : tous les container de tête dans la hiérarchie (JFrame, JWindow…) contiennent un container
intermédiaire qui se charge de contenir les fils (contentPane)




                                                                                                       3
Le code de l'exemple :


import javax.swing.*;
import java.awt.*;

public class Exemple1 {

 public static void main(String[] args) {

  JFrame frame = new JFrame(”exemple”);
  JButton button = new JButton(”clic clic”);
  JLabel label = new JLabel(”un petit texte”);
  JPanel pane = new JPanel();
  pane.add(button);
  pane.add(label);
  frame.getContentPane().add(pane, BorderLayout.CENTER);

 }
}




                                                           4
Agencer les composants avec les Layouts
Le layout par défaut : FlowLayout




Le plus utilisé : BorderLayout




Autres layouts : BoxLayout, GridLayout




                                                                     5
Utiliser le BorderLayout

⇒ Ajouter au panel avec une contrainte

frame.getContentPane().add(pane, BorderLayout.CENTER);


Exercice : modifier l'exemple pour avoir :




Remarque : définir le layout du JPanel avec pane.setLayout(new BorderLayout())




                                                                                 6
Solution :

   JFrame frame = new JFrame("exemple");
   JButton button = new JButton("clic clic");
   JLabel label = new JLabel("un petit texte");
   JButton button2 = new JButton("deuxieme bouton");
   JPanel pane = new JPanel();
   pane.setLayout(new BorderLayout());
   pane.add(button, BorderLayout.NORTH);
   pane.add(label, BorderLayout.CENTER);
   pane.add(button2, BorderLayout.SOUTH);
   frame.getContentPane().add(pane, BorderLayout.CENTER);
   frame.show();




                                                            7
Utiliser le GridLayout

⇒ Créer le layout en le définissant :

pane.setLayout(new GridLayout(3,2));


Exercice : modifier l'exemple pour avoir :




Remarque : l'ajout ne nécessite plus de contrainte : pane.add(button);




                                                                         8
Solution :

   JFrame frame = new JFrame("exemple");
   JButton button = new JButton("clic clic");
   JLabel label = new JLabel("un petit texte");
   JButton button2 = new JButton("deuxieme bouton");
   JButton button3 = new JButton("troisieme bouton");
   JButton button4 = new JButton("quatrieme bouton");
   JPanel pane = new JPanel();
   pane.setLayout(new GridLayout(3,2));
   pane.add(button);
   pane.add(label);
   pane.add(button2);
   pane.add(button3);
   pane.add(button4);
   frame.getContentPane().add(pane, BorderLayout.CENTER);
   frame.show();




                                                            9
Comment agencer de façon plus riche ?
Exercice : Comment faire :




Remarque : utilisez plus d'un panel… exemple :




- panel2
- panel3




                                                                     10
Solution possible :

  JFrame frame = new JFrame("exemple");

  JButton button1     = new JButton("bouton1");
  JLabel label1 =     new JLabel("texte1");
  JLabel label2 =     new JLabel("texte2");
  JButton button2     = new JButton("bouton2");
  JButton button3     = new JButton("bouton3");
  JButton button4     = new JButton("bouton4");
  JButton button5     = new JButton("bouton5");

  JPanel pane1 = new JPanel(new BorderLayout()); /* on peut spécifier le layout à la construction */
  JPanel pane2 = new JPanel(new BorderLayout());
  JPanel pane3 = new JPanel(new BorderLayout());

  pane1.add(button1, BorderLayout.EAST);
  pane1.add(label1, BorderLayout.WEST);
  pane1.add(pane2, BorderLayout.CENTER);

  pane2.add(button2, BorderLayout.NORTH);
  pane2.add(button3, BorderLayout.SOUTH);
  pane2.add(pane3, BorderLayout.CENTER);

  pane3.add(button4, BorderLayout.EAST);
  pane3.add(button5, BorderLayout.WEST);
  pane3.add(label2, BorderLayout.CENTER);

  frame.getContentPane().add(pane1, BorderLayout.CENTER);
  frame.show();




                                                                                                       11
Arborescence :

                              frame.getContentPane()



                                        pane1




                 button1   label1                                pane2




                                    button2            button3           pane3




                                                             button4     button5   label2




                                                                                   12
Exercices : de l'idée au code


Ecrire le code pour obtenir :




Remarque : pour créer un composant ”image” : new JLabel(new ImageIcon(”duke.gif”))




                                                                                     13
Solution possible :

   JFrame frame = new JFrame("exemple");
   JButton button1 = new JButton("ô rage");
   JButton button2 = new JButton("ô désespoir");
   JButton button3 = new JButton("ô vieillesse ennemie");

   JLabel label1 = new JLabel(new ImageIcon("duke.gif"));

   JPanel pane1 = new JPanel(new GridLayout(0, 1));
   pane1.add(button1);
   pane1.add(button2);
   pane1.add(button3);
   frame.getContentPane().add(pane1, BorderLayout.EAST);
   frame.getContentPane().add(label1, BorderLayout.CENTER);
   frame.show();

Remarque : une valeur 0 pour l'initialisation du GridLayout signifie "un nombre indéterminé" de
composants.




                                                                                                  14
Même exercice :




De même : (remarquez que Corneille et Le Cid sont centrés)




Remarque : Avez-vous remarqué le comportement du FlowLayout ?… il permet de centrer les composants…




                                                                                                 15
Solutions possibles :

 JFrame frame = new JFrame("exemple");                     JFrame frame = new JFrame("exemple");
 JButton button1 = new JButton("ô rage");                  JButton button1 = new JButton("ô rage");
 JButton button2 = new JButton("ô désespoir");             JButton button2 = new JButton("ô désespoir");
 JButton button3 = new JButton("ô vieillesse ennemie");    JButton button3 = new JButton("ô vieillesse ennemie");

 JLabel label1 = new JLabel(new ImageIcon("duke.gif"));    JLabel label1 = new JLabel(new ImageIcon("duke.gif"));
 JLabel label2 = new JLabel("Corneille");                  JLabel label2 = new JLabel("Corneille");
 JLabel label3 = new JLabel("Le Cid");                     JLabel label3 = new JLabel("Le Cid");

 JPanel pane1 = new JPanel(new GridLayout(0, 1));          JPanel pane1 = new JPanel(new GridLayout(0, 1));
 pane1.add(button1);                                       pane1.add(button1);
 pane1.add(button2);                                       pane1.add(button2);
 pane1.add(button3);                                       pane1.add(button3);

 JPanel pane2 = new JPanel(new BorderLayout());            JPanel pane2 = new JPanel(new BorderLayout());
 pane2.add(label1, BorderLayout.CENTER);                   JPanel paneNorth = new JPanel(new FlowLayout());
 pane2.add(label2, BorderLayout.NORTH);                    JPanel paneSouth = new JPanel(new FlowLayout());
 pane2.add(label3, BorderLayout.SOUTH);                    paneNorth.add(label2);
                                                           paneSouth.add(label3);
                                                           pane2.add(label1, BorderLayout.CENTER);
                                                           pane2.add(paneNorth, BorderLayout.NORTH);
                                                           pane2.add(paneSouth, BorderLayout.SOUTH);

 frame.getContentPane().add(pane1, BorderLayout.EAST);     frame.getContentPane().add(pane1, BorderLayout.EAST);
 frame.getContentPane().add(pane2, BorderLayout.CENTER);   frame.getContentPane().add(pane2, BorderLayout.CENTER);
 frame.show();                                             frame.show();




                                                                                                                     16
Réagir aux actions avec des listeners
Les composants Swing peuvent avertir d'une action effectuée sur eux-mêmes.




                                             action performed !


Pour être averti, il faut donc écrire un objet capable d'être averti.
Il faut pour cela implémenter l'interface "d'écoute" correspondant à l'événement, à l'action.
Par exemple, un JButton avertit les ActionListeners : il possède la méthode addActionListener.

class MyActionListener implements ActionListener {
  public void actionPerformed(ActionEvent event) {
   System.out.println("clicked!!"); /* ecrit sur la sortie console */
  }
}

…

JButton button = new JButton("clic clic");
button.addActionListener(new MyActionListener());


                                                                                                 17
Exemple complet :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Exemple8 {

public static void main(String[] args) {
  JFrame frame = new JFrame("exemple");
  JButton button = new JButton("clic clic");
  button.addActionListener(new MyActionListener());
  JLabel label = new JLabel("un petit texte");
  JPanel pane = new JPanel();
  pane.add(button);
  pane.add(label);
  frame.getContentPane().add(pane, BorderLayout.CENTER);
  frame.show();
}

    /* on peut écrire une class à l'intérieur d'une autre, */
    /* utilisée uniquement dans la classe englobante.      */
    static class MyActionListener implements ActionListener {
      public void actionPerformed(ActionEvent event) {
        System.out.println("clicked!!");
      }
    }
}


                                                                18
Exercice :

Modifier le programme suivant pour que le label affiche le nombre d'appuis sur le bouton.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Exemple9 {

    private JLabel label;

    public Exemple9() {
      JFrame frame = new JFrame("exemple");
      JButton button = new JButton("clic clic");
      button.addActionListener(new MyActionListener());
      label = new JLabel("0");
      JPanel pane = new JPanel();
      pane.add(button);
      pane.add(label);
      frame.getContentPane().add(pane, BorderLayout.CENTER);
      frame.show();
    }

    private class MyActionListener implements ActionListener {
      public void actionPerformed(ActionEvent event) {
        //…
      }
    }

    public static void main(String[] args) {
      new Exemple9();
    }
}


Remarque : on peut modifier le texte d'un label avec label.setText(”...”)

                                                                                            19
Solution :

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Exemple9 {

    private int count = 0;
    private JLabel label;

    public Exemple9() {
      JFrame frame = new JFrame("exemple");
      JButton button = new JButton("clic clic");
      button.addActionListener(new MyActionListener());
      label = new JLabel("0");
      JPanel pane = new JPanel();
      pane.add(button);
      pane.add(label);
      frame.getContentPane().add(pane, BorderLayout.CENTER);
      frame.show();
    }

    /* classe qui accède à count; count appartient à la classe englobante */
    private class MyActionListener implements ActionListener {
      public void actionPerformed(ActionEvent event) {
        count++;
        label.setText(Integer.toString(count));
      }
    }

    public static void main(String[] args) {
      new Exemple9();
    }
}




                                                                               20
Comment connaître les listeners associés aux composants ?

- avec une liste exhaustive (voir tutorial Sun)
- en repérant dans la documentation les méthodes "addXXXListener"


Exercice :

1) Trouvez le listener associé aux événements de fenêtre (fermeture, réduction…) pour JFrame
2) Modifier le programme précédent pour qu'il s'arrête lorsque l'on ferme la fenêtre


Remarque :
Pour quitter : System.exit(0);




                                                                                               21
Solution :

Il faut implémenter WindowListener
public Exemple10() {
    JFrame frame = new JFrame("exemple");
    frame.addWindowListener(new MyWindowListener());
    JButton button = new JButton("clic clic");
    ...
    frame.show();
  }

  private class MyActionListener implements ActionListener {
    ...
  }

  private class MyWindowListener implements WindowListener {
    public void windowActivated(WindowEvent event) {
    }
    public void windowDeactivated(WindowEvent event) {
    }
    public void windowClosing(WindowEvent event) {
      System.exit(0);
    }
    public void windowClosed(WindowEvent event) {
    }
    public void windowIconified(WindowEvent event) {
    }
    public void windowDeiconified(WindowEvent event) {
    }
    public void windowOpened(WindowEvent event) {
    }
  }

...
}




                                                               22
Lorsque l'on utilise qu'une partie de l'interface d'écoute : les Adapters
Dans l'exemple précédent, seule la méthode "windowClosing" nous a été utile.
Mais il a fallu pourtant implémenter (avec rien!) les autres méthodes de l'interface.
Par facilité, on peut utiliser la classe WindowAdapter qui est le WindowListener le plus simple : il ne fait
rien.
Il suffit alors de redéfinir par héritage la méthode voulue.

private class MyWindowListener extends WindowAdapter {
    public void windowClosing(WindowEvent event) {
      System.exit(0);
    }
}

Schéma général :
                                                                     Question :
                                                                     Pourquoi n'existe-t-il pas de ActionAdapter ?
                     _XXX_Listener


    My_XXX_Listener                   _XXX_Adapter
        on
        implémente
        toutes les
        méthodes
                                     My_XXX_Listener
                                         on
                                         implémente
                                         certaines
                                         méthodes
                                                                                                                     23
Utiliser les événements
Lors d'un click, d'une modification, etc., l'objet avertit ses listeners en envoyant un event.

Par exemple :
 actionPerformed(ActionEvent event)

Cet event englobe des informations que l'on peut récupérer pour réagir en fonction de ces informations.

Par exemple, on peut "brancher" deux boutons sur le même listener et vouloir réagir différemment aux deux
boutons.

button1 = new JButton();
button2 = new JButton();
ActionListener myActionListener = new ActionListener();
button1.addActionListener(myActionListener);
button2.addActionListener(myActionListener);
…
class MyActionListener implements ActionListener {
  public void actionPerformed(ActionEvent event) {
    if(event.getSource() == button1) {
       // button1 clicked
    } else {
      // button2 clicked
    }
  }
}



                                                                                                          24
Exercice :


Modifier le programme précédent afin qu'un bouton incrémente le compteur et qu'un autre bouton le
décrémente.




                                                                                                    25
Solution :

public class Exemple11 {
  private int count = 0;
  private JLabel label;
  private JButton buttonPlus;
  private JButton buttonMoins;

  public Exemple11() {
    JFrame frame = new JFrame("exemple");
    frame.addWindowListener(new MyWindowListener());
    buttonPlus = new JButton("plus");
    buttonMoins = new JButton("moins");
    buttonPlus.addActionListener(new MyActionListener());
    buttonMoins.addActionListener(new MyActionListener());
    label = new JLabel("0", SwingConstants.CENTER);
    JPanel pane = new JPanel(new BorderLayout());
    JPanel buttons = new JPanel(new GridLayout(0, 1));
    buttons.add(buttonPlus);
    buttons.add(buttonMoins);
    pane.add(buttons, BorderLayout.WEST);
    pane.add(label, BorderLayout.CENTER);
    frame.getContentPane().add(pane, BorderLayout.CENTER);
    frame.show();
  }

  private class MyActionListener implements ActionListener {
    public void actionPerformed(ActionEvent event) {
      if(event.getSource() == buttonPlus) {
        count++;
      } else {
        count--;
      }
      label.setText(Integer.toString(count));
    }
  }
...
}



                                                               26
Plus de fonctionnalités !
Dans une JFrame, on peut définir sa barre de menu avec JMenuBar, JMenu et JMenuItem.

Exemple :




                                                                                       27
Programme :

    JFrame frame = new JFrame("exemple");

    JMenuBar menuBar = new JMenuBar();
    JMenu menu = new JMenu("File");
    JMenu submenu = new JMenu("Property");

    menu.add(new JMenuItem("New"));
    menu.add(new JMenuItem("Open"));
    menu.add(new JMenuItem("Save"));
    menu.add(new JSeparator());
    menu.add(submenu);

    submenu.add(new JMenuItem("Big"));
    submenu.add(new JMenuItem("Small"));

    menuBar.add(menu);

    frame.setJMenuBar(menuBar);
    frame.show();




                                             28
Hiérarchie des composants :




Remarquez que ce schéma exprime qu'un JMenu est un JMenuItem : lorsqu'un menu est employé en tant
qu'item, il a le comportement d'un sous-menu.



                                                                                                    29
Exercice :


1) Trouvez comment réagir à la sélection d'un item du menu.
2) Modifier l'exemple précédent pour qu'un label de la fenêtre affiche le dernier item selectionné.


3) Modifier à nouveau votre programme en remplaçant le label par une zone de texte qui affiche l'historique
   des sélections des items.


Remarque :
- il vous faudra regarder la documentation de JMenuItem notamment.
- pour le point 3, il vous faudra regarder JTextArea.




                                                                                                          30
Solution 2) :

public class Exemple13 {
  private JMenuItem item1, item2, item3, item4, item5;
  private JLabel label;

  public Exemple13() {
    JFrame frame = new JFrame("exemple");
    frame.addWindowListener(new MyWindowListener());

    JMenuBar menuBar = new JMenuBar();
    JMenu menu = new JMenu("File");
    JMenu submenu = new JMenu("Property");

    item1   =   new   JMenuItem("New");
    item2   =   new   JMenuItem("Open");
    item3   =   new   JMenuItem("Save");
    item4   =   new   JMenuItem("Big");
    item5   =   new   JMenuItem("Small");

    MyActionListener listener = new MyActionListener();
    item1.addActionListener(listener);
    item2.addActionListener(listener);
    item3.addActionListener(listener);
    item4.addActionListener(listener);
    item5.addActionListener(listener);

    menu.add(item1);
    menu.add(item2);
    menu.add(item3);
    menu.add(new JSeparator());
    menu.add(submenu);

    submenu.add(item4);
    submenu.add(item5);

    menuBar.add(menu);




                                                          31
label = new JLabel("-");

        frame.setJMenuBar(menuBar);
        frame.getContentPane().add(label);
        frame.show();
    }

    private class MyWindowListener extends WindowAdapter {
      public void windowClosing(WindowEvent event) {
        System.exit(0);
      }
    }

    private class MyActionListener implements ActionListener {
      public void actionPerformed(ActionEvent event) {
        label.setText(((JMenuItem)event.getSource()).getText());
      }
    }

    public static void main(String[] args) {
      new Exemple13();
    }
}




                                                                   32
Solution 3) :

private JMenuItem item1, item2, item3, item4, item5;
private JTextArea text;


…
text = new JTextArea();

frame.setJMenuBar(menuBar);
frame.getContentPane().add(text);
frame.show();
…
private class MyActionListener implements ActionListener {
    public void actionPerformed(ActionEvent event) {
      text.append(((JMenuItem)event.getSource()).getText() + "n");
    }
}




                                                                      33
Exercice
Il s'agit de créer un programme qui possède une fenêtre principale où l'on tape du texte, et une fenêtre
secondaire où le texte est envoyé, ligne par ligne.

La fenêtre principale contiendra une zone de texte éditable où l'utilisateur tapera la ligne à envoyer, ainsi
qu'un bouton d'envoi.
Elle permettra aussi de fermer le programme.

La fenêtre secondaire ne possèdera pas de barre de menu (regarder JWindow). Elle contiendra une zone de
texte non éditable où le texte reçu sera écrit.


                                                                    le texte reçu est affiché ici…
  Fichier | Options




           Fenêtre principale




   écrivez ici…




              Envoyer

                                                                                                                34
Remarques :

- pour régler la taille de la fenêtre : setSize(200, 200)

- pour positionner la fenêtre : setLocation(400, 0)

- pour créer un panel scrollable : scroll = new JScrollPane(panel); panel2.add(scroll);




                                                                                          35
Solution :

public class Exemple15 {

  private JTextArea text, area;

  public Exemple15() {
    JFrame frame = new JFrame("exemple");
    frame.addWindowListener(new MyWindowListener());

      text = new JTextArea();
      text.setEditable(false);

      JWindow window = new JWindow(frame);
      JPanel panel = new JPanel(new BorderLayout());
      panel.add(text, BorderLayout.CENTER);
      JScrollPane scroll = new JScrollPane(panel);
      window.getContentPane().add(scroll);

      JPanel panel2 = new JPanel(new BorderLayout());
      area = new JTextArea();
      panel2.add(area, BorderLayout.CENTER);

      JPanel panel3 = new JPanel(new BorderLayout());
      JButton button = new JButton("Envoyer");
      panel3.add(new JScrollPane(panel2), BorderLayout.CENTER);
      panel3.add(button, BorderLayout.SOUTH);

      button.addActionListener(new MyActionListener());

      frame.getContentPane().add(panel3);
      frame.setSize(200, 200);
      window.setSize(200, 200);
      frame.setLocation(0, 0);
      window.setLocation(400, 0);
      frame.show();
      window.show();
  }



                                                                  36
private class MyWindowListener extends WindowAdapter {
      public void windowClosing(WindowEvent event) {
        System.exit(0);
      }
    }

    private class MyActionListener implements ActionListener {
      public void actionPerformed(ActionEvent event) {
        text.append(area.getText() + "n");
        area.setText("");
      }
    }

    public static void main(String[] args) {
      new Exemple15();
    }
}




                                                                 37

Weitere ähnliche Inhalte

Empfohlen

Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at WorkGetSmarter
 

Empfohlen (20)

Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 

00 swing

  • 1. Créer des interfaces utilisateurs avec Java et Swing 1
  • 2. Premier exemple. Nous utilisons ici les composants les plus communs d'une interface. Leur traduction en Swing : - Une fenêtre principale (avec boutons d'agrandissement, réduction, fermeture…) : JFrame - Un plan rectangulaire : JPanel - Un bouton : Jbutton - Une zone texte : Jlabel 2
  • 3. Le modèle par Container La JFrame est un composant qui contient tous les autres. Le JPanel est un container intermédiaire qui va se charger de contenir le label et le bouton. Le JButton et le JLabel sont des composants atomiques. Autres exemples : zone de texte éditable (JTextField), table (JTable), etc… Diagramme de hiérarchie (contenance) – arborescence : Remarque : tous les container de tête dans la hiérarchie (JFrame, JWindow…) contiennent un container intermédiaire qui se charge de contenir les fils (contentPane) 3
  • 4. Le code de l'exemple : import javax.swing.*; import java.awt.*; public class Exemple1 { public static void main(String[] args) { JFrame frame = new JFrame(”exemple”); JButton button = new JButton(”clic clic”); JLabel label = new JLabel(”un petit texte”); JPanel pane = new JPanel(); pane.add(button); pane.add(label); frame.getContentPane().add(pane, BorderLayout.CENTER); } } 4
  • 5. Agencer les composants avec les Layouts Le layout par défaut : FlowLayout Le plus utilisé : BorderLayout Autres layouts : BoxLayout, GridLayout 5
  • 6. Utiliser le BorderLayout ⇒ Ajouter au panel avec une contrainte frame.getContentPane().add(pane, BorderLayout.CENTER); Exercice : modifier l'exemple pour avoir : Remarque : définir le layout du JPanel avec pane.setLayout(new BorderLayout()) 6
  • 7. Solution : JFrame frame = new JFrame("exemple"); JButton button = new JButton("clic clic"); JLabel label = new JLabel("un petit texte"); JButton button2 = new JButton("deuxieme bouton"); JPanel pane = new JPanel(); pane.setLayout(new BorderLayout()); pane.add(button, BorderLayout.NORTH); pane.add(label, BorderLayout.CENTER); pane.add(button2, BorderLayout.SOUTH); frame.getContentPane().add(pane, BorderLayout.CENTER); frame.show(); 7
  • 8. Utiliser le GridLayout ⇒ Créer le layout en le définissant : pane.setLayout(new GridLayout(3,2)); Exercice : modifier l'exemple pour avoir : Remarque : l'ajout ne nécessite plus de contrainte : pane.add(button); 8
  • 9. Solution : JFrame frame = new JFrame("exemple"); JButton button = new JButton("clic clic"); JLabel label = new JLabel("un petit texte"); JButton button2 = new JButton("deuxieme bouton"); JButton button3 = new JButton("troisieme bouton"); JButton button4 = new JButton("quatrieme bouton"); JPanel pane = new JPanel(); pane.setLayout(new GridLayout(3,2)); pane.add(button); pane.add(label); pane.add(button2); pane.add(button3); pane.add(button4); frame.getContentPane().add(pane, BorderLayout.CENTER); frame.show(); 9
  • 10. Comment agencer de façon plus riche ? Exercice : Comment faire : Remarque : utilisez plus d'un panel… exemple : - panel2 - panel3 10
  • 11. Solution possible : JFrame frame = new JFrame("exemple"); JButton button1 = new JButton("bouton1"); JLabel label1 = new JLabel("texte1"); JLabel label2 = new JLabel("texte2"); JButton button2 = new JButton("bouton2"); JButton button3 = new JButton("bouton3"); JButton button4 = new JButton("bouton4"); JButton button5 = new JButton("bouton5"); JPanel pane1 = new JPanel(new BorderLayout()); /* on peut spécifier le layout à la construction */ JPanel pane2 = new JPanel(new BorderLayout()); JPanel pane3 = new JPanel(new BorderLayout()); pane1.add(button1, BorderLayout.EAST); pane1.add(label1, BorderLayout.WEST); pane1.add(pane2, BorderLayout.CENTER); pane2.add(button2, BorderLayout.NORTH); pane2.add(button3, BorderLayout.SOUTH); pane2.add(pane3, BorderLayout.CENTER); pane3.add(button4, BorderLayout.EAST); pane3.add(button5, BorderLayout.WEST); pane3.add(label2, BorderLayout.CENTER); frame.getContentPane().add(pane1, BorderLayout.CENTER); frame.show(); 11
  • 12. Arborescence : frame.getContentPane() pane1 button1 label1 pane2 button2 button3 pane3 button4 button5 label2 12
  • 13. Exercices : de l'idée au code Ecrire le code pour obtenir : Remarque : pour créer un composant ”image” : new JLabel(new ImageIcon(”duke.gif”)) 13
  • 14. Solution possible : JFrame frame = new JFrame("exemple"); JButton button1 = new JButton("ô rage"); JButton button2 = new JButton("ô désespoir"); JButton button3 = new JButton("ô vieillesse ennemie"); JLabel label1 = new JLabel(new ImageIcon("duke.gif")); JPanel pane1 = new JPanel(new GridLayout(0, 1)); pane1.add(button1); pane1.add(button2); pane1.add(button3); frame.getContentPane().add(pane1, BorderLayout.EAST); frame.getContentPane().add(label1, BorderLayout.CENTER); frame.show(); Remarque : une valeur 0 pour l'initialisation du GridLayout signifie "un nombre indéterminé" de composants. 14
  • 15. Même exercice : De même : (remarquez que Corneille et Le Cid sont centrés) Remarque : Avez-vous remarqué le comportement du FlowLayout ?… il permet de centrer les composants… 15
  • 16. Solutions possibles : JFrame frame = new JFrame("exemple"); JFrame frame = new JFrame("exemple"); JButton button1 = new JButton("ô rage"); JButton button1 = new JButton("ô rage"); JButton button2 = new JButton("ô désespoir"); JButton button2 = new JButton("ô désespoir"); JButton button3 = new JButton("ô vieillesse ennemie"); JButton button3 = new JButton("ô vieillesse ennemie"); JLabel label1 = new JLabel(new ImageIcon("duke.gif")); JLabel label1 = new JLabel(new ImageIcon("duke.gif")); JLabel label2 = new JLabel("Corneille"); JLabel label2 = new JLabel("Corneille"); JLabel label3 = new JLabel("Le Cid"); JLabel label3 = new JLabel("Le Cid"); JPanel pane1 = new JPanel(new GridLayout(0, 1)); JPanel pane1 = new JPanel(new GridLayout(0, 1)); pane1.add(button1); pane1.add(button1); pane1.add(button2); pane1.add(button2); pane1.add(button3); pane1.add(button3); JPanel pane2 = new JPanel(new BorderLayout()); JPanel pane2 = new JPanel(new BorderLayout()); pane2.add(label1, BorderLayout.CENTER); JPanel paneNorth = new JPanel(new FlowLayout()); pane2.add(label2, BorderLayout.NORTH); JPanel paneSouth = new JPanel(new FlowLayout()); pane2.add(label3, BorderLayout.SOUTH); paneNorth.add(label2); paneSouth.add(label3); pane2.add(label1, BorderLayout.CENTER); pane2.add(paneNorth, BorderLayout.NORTH); pane2.add(paneSouth, BorderLayout.SOUTH); frame.getContentPane().add(pane1, BorderLayout.EAST); frame.getContentPane().add(pane1, BorderLayout.EAST); frame.getContentPane().add(pane2, BorderLayout.CENTER); frame.getContentPane().add(pane2, BorderLayout.CENTER); frame.show(); frame.show(); 16
  • 17. Réagir aux actions avec des listeners Les composants Swing peuvent avertir d'une action effectuée sur eux-mêmes. action performed ! Pour être averti, il faut donc écrire un objet capable d'être averti. Il faut pour cela implémenter l'interface "d'écoute" correspondant à l'événement, à l'action. Par exemple, un JButton avertit les ActionListeners : il possède la méthode addActionListener. class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent event) { System.out.println("clicked!!"); /* ecrit sur la sortie console */ } } … JButton button = new JButton("clic clic"); button.addActionListener(new MyActionListener()); 17
  • 18. Exemple complet : import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Exemple8 { public static void main(String[] args) { JFrame frame = new JFrame("exemple"); JButton button = new JButton("clic clic"); button.addActionListener(new MyActionListener()); JLabel label = new JLabel("un petit texte"); JPanel pane = new JPanel(); pane.add(button); pane.add(label); frame.getContentPane().add(pane, BorderLayout.CENTER); frame.show(); } /* on peut écrire une class à l'intérieur d'une autre, */ /* utilisée uniquement dans la classe englobante. */ static class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent event) { System.out.println("clicked!!"); } } } 18
  • 19. Exercice : Modifier le programme suivant pour que le label affiche le nombre d'appuis sur le bouton. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Exemple9 { private JLabel label; public Exemple9() { JFrame frame = new JFrame("exemple"); JButton button = new JButton("clic clic"); button.addActionListener(new MyActionListener()); label = new JLabel("0"); JPanel pane = new JPanel(); pane.add(button); pane.add(label); frame.getContentPane().add(pane, BorderLayout.CENTER); frame.show(); } private class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent event) { //… } } public static void main(String[] args) { new Exemple9(); } } Remarque : on peut modifier le texte d'un label avec label.setText(”...”) 19
  • 20. Solution : import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Exemple9 { private int count = 0; private JLabel label; public Exemple9() { JFrame frame = new JFrame("exemple"); JButton button = new JButton("clic clic"); button.addActionListener(new MyActionListener()); label = new JLabel("0"); JPanel pane = new JPanel(); pane.add(button); pane.add(label); frame.getContentPane().add(pane, BorderLayout.CENTER); frame.show(); } /* classe qui accède à count; count appartient à la classe englobante */ private class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent event) { count++; label.setText(Integer.toString(count)); } } public static void main(String[] args) { new Exemple9(); } } 20
  • 21. Comment connaître les listeners associés aux composants ? - avec une liste exhaustive (voir tutorial Sun) - en repérant dans la documentation les méthodes "addXXXListener" Exercice : 1) Trouvez le listener associé aux événements de fenêtre (fermeture, réduction…) pour JFrame 2) Modifier le programme précédent pour qu'il s'arrête lorsque l'on ferme la fenêtre Remarque : Pour quitter : System.exit(0); 21
  • 22. Solution : Il faut implémenter WindowListener public Exemple10() { JFrame frame = new JFrame("exemple"); frame.addWindowListener(new MyWindowListener()); JButton button = new JButton("clic clic"); ... frame.show(); } private class MyActionListener implements ActionListener { ... } private class MyWindowListener implements WindowListener { public void windowActivated(WindowEvent event) { } public void windowDeactivated(WindowEvent event) { } public void windowClosing(WindowEvent event) { System.exit(0); } public void windowClosed(WindowEvent event) { } public void windowIconified(WindowEvent event) { } public void windowDeiconified(WindowEvent event) { } public void windowOpened(WindowEvent event) { } } ... } 22
  • 23. Lorsque l'on utilise qu'une partie de l'interface d'écoute : les Adapters Dans l'exemple précédent, seule la méthode "windowClosing" nous a été utile. Mais il a fallu pourtant implémenter (avec rien!) les autres méthodes de l'interface. Par facilité, on peut utiliser la classe WindowAdapter qui est le WindowListener le plus simple : il ne fait rien. Il suffit alors de redéfinir par héritage la méthode voulue. private class MyWindowListener extends WindowAdapter { public void windowClosing(WindowEvent event) { System.exit(0); } } Schéma général : Question : Pourquoi n'existe-t-il pas de ActionAdapter ? _XXX_Listener My_XXX_Listener _XXX_Adapter on implémente toutes les méthodes My_XXX_Listener on implémente certaines méthodes 23
  • 24. Utiliser les événements Lors d'un click, d'une modification, etc., l'objet avertit ses listeners en envoyant un event. Par exemple : actionPerformed(ActionEvent event) Cet event englobe des informations que l'on peut récupérer pour réagir en fonction de ces informations. Par exemple, on peut "brancher" deux boutons sur le même listener et vouloir réagir différemment aux deux boutons. button1 = new JButton(); button2 = new JButton(); ActionListener myActionListener = new ActionListener(); button1.addActionListener(myActionListener); button2.addActionListener(myActionListener); … class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent event) { if(event.getSource() == button1) { // button1 clicked } else { // button2 clicked } } } 24
  • 25. Exercice : Modifier le programme précédent afin qu'un bouton incrémente le compteur et qu'un autre bouton le décrémente. 25
  • 26. Solution : public class Exemple11 { private int count = 0; private JLabel label; private JButton buttonPlus; private JButton buttonMoins; public Exemple11() { JFrame frame = new JFrame("exemple"); frame.addWindowListener(new MyWindowListener()); buttonPlus = new JButton("plus"); buttonMoins = new JButton("moins"); buttonPlus.addActionListener(new MyActionListener()); buttonMoins.addActionListener(new MyActionListener()); label = new JLabel("0", SwingConstants.CENTER); JPanel pane = new JPanel(new BorderLayout()); JPanel buttons = new JPanel(new GridLayout(0, 1)); buttons.add(buttonPlus); buttons.add(buttonMoins); pane.add(buttons, BorderLayout.WEST); pane.add(label, BorderLayout.CENTER); frame.getContentPane().add(pane, BorderLayout.CENTER); frame.show(); } private class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent event) { if(event.getSource() == buttonPlus) { count++; } else { count--; } label.setText(Integer.toString(count)); } } ... } 26
  • 27. Plus de fonctionnalités ! Dans une JFrame, on peut définir sa barre de menu avec JMenuBar, JMenu et JMenuItem. Exemple : 27
  • 28. Programme : JFrame frame = new JFrame("exemple"); JMenuBar menuBar = new JMenuBar(); JMenu menu = new JMenu("File"); JMenu submenu = new JMenu("Property"); menu.add(new JMenuItem("New")); menu.add(new JMenuItem("Open")); menu.add(new JMenuItem("Save")); menu.add(new JSeparator()); menu.add(submenu); submenu.add(new JMenuItem("Big")); submenu.add(new JMenuItem("Small")); menuBar.add(menu); frame.setJMenuBar(menuBar); frame.show(); 28
  • 29. Hiérarchie des composants : Remarquez que ce schéma exprime qu'un JMenu est un JMenuItem : lorsqu'un menu est employé en tant qu'item, il a le comportement d'un sous-menu. 29
  • 30. Exercice : 1) Trouvez comment réagir à la sélection d'un item du menu. 2) Modifier l'exemple précédent pour qu'un label de la fenêtre affiche le dernier item selectionné. 3) Modifier à nouveau votre programme en remplaçant le label par une zone de texte qui affiche l'historique des sélections des items. Remarque : - il vous faudra regarder la documentation de JMenuItem notamment. - pour le point 3, il vous faudra regarder JTextArea. 30
  • 31. Solution 2) : public class Exemple13 { private JMenuItem item1, item2, item3, item4, item5; private JLabel label; public Exemple13() { JFrame frame = new JFrame("exemple"); frame.addWindowListener(new MyWindowListener()); JMenuBar menuBar = new JMenuBar(); JMenu menu = new JMenu("File"); JMenu submenu = new JMenu("Property"); item1 = new JMenuItem("New"); item2 = new JMenuItem("Open"); item3 = new JMenuItem("Save"); item4 = new JMenuItem("Big"); item5 = new JMenuItem("Small"); MyActionListener listener = new MyActionListener(); item1.addActionListener(listener); item2.addActionListener(listener); item3.addActionListener(listener); item4.addActionListener(listener); item5.addActionListener(listener); menu.add(item1); menu.add(item2); menu.add(item3); menu.add(new JSeparator()); menu.add(submenu); submenu.add(item4); submenu.add(item5); menuBar.add(menu); 31
  • 32. label = new JLabel("-"); frame.setJMenuBar(menuBar); frame.getContentPane().add(label); frame.show(); } private class MyWindowListener extends WindowAdapter { public void windowClosing(WindowEvent event) { System.exit(0); } } private class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent event) { label.setText(((JMenuItem)event.getSource()).getText()); } } public static void main(String[] args) { new Exemple13(); } } 32
  • 33. Solution 3) : private JMenuItem item1, item2, item3, item4, item5; private JTextArea text; … text = new JTextArea(); frame.setJMenuBar(menuBar); frame.getContentPane().add(text); frame.show(); … private class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent event) { text.append(((JMenuItem)event.getSource()).getText() + "n"); } } 33
  • 34. Exercice Il s'agit de créer un programme qui possède une fenêtre principale où l'on tape du texte, et une fenêtre secondaire où le texte est envoyé, ligne par ligne. La fenêtre principale contiendra une zone de texte éditable où l'utilisateur tapera la ligne à envoyer, ainsi qu'un bouton d'envoi. Elle permettra aussi de fermer le programme. La fenêtre secondaire ne possèdera pas de barre de menu (regarder JWindow). Elle contiendra une zone de texte non éditable où le texte reçu sera écrit. le texte reçu est affiché ici… Fichier | Options Fenêtre principale écrivez ici… Envoyer 34
  • 35. Remarques : - pour régler la taille de la fenêtre : setSize(200, 200) - pour positionner la fenêtre : setLocation(400, 0) - pour créer un panel scrollable : scroll = new JScrollPane(panel); panel2.add(scroll); 35
  • 36. Solution : public class Exemple15 { private JTextArea text, area; public Exemple15() { JFrame frame = new JFrame("exemple"); frame.addWindowListener(new MyWindowListener()); text = new JTextArea(); text.setEditable(false); JWindow window = new JWindow(frame); JPanel panel = new JPanel(new BorderLayout()); panel.add(text, BorderLayout.CENTER); JScrollPane scroll = new JScrollPane(panel); window.getContentPane().add(scroll); JPanel panel2 = new JPanel(new BorderLayout()); area = new JTextArea(); panel2.add(area, BorderLayout.CENTER); JPanel panel3 = new JPanel(new BorderLayout()); JButton button = new JButton("Envoyer"); panel3.add(new JScrollPane(panel2), BorderLayout.CENTER); panel3.add(button, BorderLayout.SOUTH); button.addActionListener(new MyActionListener()); frame.getContentPane().add(panel3); frame.setSize(200, 200); window.setSize(200, 200); frame.setLocation(0, 0); window.setLocation(400, 0); frame.show(); window.show(); } 36
  • 37. private class MyWindowListener extends WindowAdapter { public void windowClosing(WindowEvent event) { System.exit(0); } } private class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent event) { text.append(area.getText() + "n"); area.setText(""); } } public static void main(String[] args) { new Exemple15(); } } 37