PROB Programmation orientée objet
Transcription
PROB Programmation orientée objet
PROB Programmation orientée objet Leçon 13 : Introduction à Swing (1) Composants, conteneurs et mise en page Gestion des événements http://docs.oracle.com/javase/tutorial/uiswing/index.html 2012/2013 EPFC - PROB - A.Silovy et B.Verhaegen 1 AWT et Swing Les packages java.awt et javax.swing fournissent les classes nécessaires pour réaliser une interface graphique (GUI, Graphical User Interface). Ces classes peuvent être organisées en 3 groupes : Les composants (élément affichable : JButton, JTextField, …) Les conteneurs (composant qui peut contenir d'autres composants : JFrame, JPanel, …) Les classes auxiliaires (Color, Font, LayoutManager, …) 2012/2013 EPFC - PROB - A.Silovy et B.Verhaegen 2 AWT et Swing : hiérarchie Swing utilise AWT mais est plus récent et plus stable. Les classes Swing commencent par un "J". 12.3 The Java GUI API Dimension Font LayoutManager 1 Classes in the java.awt package 407 Heavyweight FontMetrics Object Color Panel Applet JApplet Window Frame JFrame Dialog JDialog Graphics Component Container * JComponent Lightweight Swing GUI components such as JButton, JLabel, Swing Components JTextField, JPanel, in the javax.swing etc. package - PROB - A.Silovy et B.Verhaegen FIGURE2012/2013 12.1 Java GUI programming utilizesEPFC the classes shown in this hierarchical diagram. Source : Introduction to Java Programming, Liang 3 Sets the upper-left-corner location of the frame. Sets true to display the frame. sible: boolean): void 410 Chapter 12 GUI Basics Specifies the operation when the frame is closed. seOperation(mode: int): void Sets the location of the frame relative to the specified component. lativeTo(c: Component): 12.4.2 If Adding Components to frame a Frame the component is null, the is centered on the screen. The frameAutomatically shown in Figuresets 12.3(a) is empty. Using the you caninadd the frame size to holdadd themethod, components thecomponents into the frame, as in Listing 12.2. frame. : int, y: int): void Exemple de fenêtre contenant un bouton LISTING 12.2 MyFrameWithComponents.java e is a top-level container to hold GUI components. 1 import javax.swing.*; 2 3 public class MyFrameWithComponents { 4 public static void main(String[] args) { isplayed until the frame.setVisible(true) method is invoked. 5 JFrame frame = new JFrame("MyFrameWithComponents"); 00, 300) specifies that the frame is 400 pixels wide and 300 pixels 6 7 Add to a button e method is not used, the frame will be//sized displayinto justthe theframe title bar. create a button JButton jbtOK = new JButton("OK"); 8 nd setVisible in the Component class, they frame.add(jbtOK); add to framemethods are both 9 defined 10 that these methods are also useful in JFrame class. Later you will see 11 frame.setSize(400, 300); set size es of Component . 12 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); exit upon closing window 13 center the frame e MyFrame program, a window will frame.setLocationRelativeTo(null); be displayed on the screen (see // Center the frame 14 frame.setVisible(true); set visible 15 } 16 } Each JFrame contains a content pane. A content pane is an instance of java.awt.Container. The GUI components such as buttons are placed in the content pane in a frame. In earlier version Title bar of Java, you had to use the getContentPane method in the JFrame class to return the content pane of the frame, then invoke the content pane’s add method to place Content a component into the content pane, as follows: pane (a) e program creates and displays 2012/2013 java.awt.Container container = frame.getContentPane(); container.add(jbtOK); (b) This was cumbersome. The new version of Java since Java 5 allows you to place components the content by invoking as follows: ainto frame with pane the title MyFrame . (b)add OK button is added to the EPFC - PROBa-frame’s A.Silovy etAn B.method, Verhaegen Source : Introduction to Java Programming, Liang frame.add(jbtOK); 4 Bonnes pratiques Une bonne pratique lors de l'écriture d'une fenêtre est : 1. de sous-classer JFrame et de définir ses composants comme attributs 2. de lancer la fenêtre dans le thread du GUI (voir plus loin). 2012/2013 EPFC - PROB - A.Silovy et B.Verhaegen 5 Les LayoutManagers Chaque conteneur contient un LayoutManager qui est responsable de mettre en page ses composants. FlowLayout : Organise les composants dans un ordre naturel (par exemple de gauche à droite) et passe à la ligne si nécessaire. GridLayout : Organise les composants dans un tableau. BorderLayout : Organise les composants par zone (haut, bas, centre, gauche, droite). Par défaut, le contentPane (Conteneur) d'une JFrame dimensionne le dernier composant ajouté pour qu'il occupe tout l'espace disponible. EPFC - PROB - A.Silovy et B.Verhaegen 6 2012/2013 Exemple de FlowLayout 2012/2013 EPFC - PROB - A.Silovy et B.Verhaegen 7 Exemple de GridLayout 2012/2013 EPFC - PROB - A.Silovy et B.Verhaegen 8 Exemple de BorderLayout 2012/2013 EPFC - PROB - A.Silovy et B.Verhaegen 9 27 28 29 30 31 32 33 34 35 36 37 38 39 40 } add(new JButton("Food to be placed here"), BorderLayout.CENTER); } /** Main method */ public static void main(String[] args) { TestPanels frame = new TestPanels(); frame.setTitle("The Front View of a Microwave Oven"); frame.setSize(400, 250); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } Utiliser un JPanel comme sous-conteneur JPanel est le conteneur standard de Swing. Comme un conteneur est un composant, on peut placer un conteneur dans un conteneur. Frame Content panel Button Panel p2 Panel p1 FIGURE 12.10 The program uses panels to organize components. The setLayout method is defined in java.awt.Container. Since JPanel is a subclass of 2012/2013 EPFC - PROB B.Verhaegen 10 Container , you can use setLayout to set- A.Silovy a newetlayout manager in the panel (line 8). Lines Source to Java Programming, Liang 7–8 can be replaced by JPanel p1: Introduction = new JPanel(new GridLayout(4, 3)). To achieve the desired layout, the program uses panel p1 of GridLayout to group the Evénements et gestionnaires d'événements. Quand un utilisateur manipule un composant, un événement est déclenché. Par exemple, lors d'un clic sur un bouton, un ActionEvent est déclenché sur ce bouton. Un gestionnaire d’évenement est nécessaire pour y réagir. Pour décrire un gestionnaire d'événement, il faut implémenter l’interface ActionListener et sa méthode actionPerformed(ActionEvent e) public class GUI{ JButton button; public GUI(){ ... button.addActionListener(new MyActionListener()); ... } public class MyActionListener implements ActionListener { La méthode } public void actionPerformed(ActionEvent e) { // Toute instruction à exécuter quand le bouton est pressé } } 2012/2013 EPFC - PROB - A.Silovy et B.Verhaegen actionPerfomed est appellée à chaque fois que l’on clique sur le bouton 11 Exemple : gestionnaire à l'aide d'une classe interne anonyme JTextField jtName 2012/2013 JButton jbtOK EPFC - PROB - A.Silovy et B.Verhaegen 12 Types d’événements Les composants peuvent déclencher des événements différents. Le plus simple à utiliser et le plus courant est l’événement Action. Par contre, un JColorChooser peut déclencher un événement de type Change qui est un peu différent (pour lequel il faudra implémenter ChangeListener). Idem pour la souris qui peut déclencher des événements Mouse ou MouseMotion. Lors de l’utilisation d’un composant particuler, il est donc utile de consulter sa documentation et celle de chaque événement qu’il peut déclencher : http://docs.oracle.com/javase/tutorial/uiswing/components/componentlist.html http://docs.oracle.com/javase/tutorial/uiswing/events/index.html 2012/2013 EPFC - PROB - A.Silovy et B.Verhaegen 13