Interfaces Graphiques

publicité
•Interfaces Graphiques
1
•java.awt : le premier package pour réaliser des interfaces
graphiques, mais les composants AWT utilisent les ressources
du système d’exploitation
•javax.swing est portable. les exécutions sont moins rapides
import java.awt.*;
import javax.swing.*;
les classes du swing hérite la classe Container du awt
(la classe qui contient les composants graphiques)
elles commencent par la lettre J majuscule
2
Swing une version améliorée de AWT mais ne le remplace pas
(certaines classes de awt est utilisées dans swing)
GUI (graphical user interface ) programmation événementielle
événement (event) est un objet qui signale un événement
à un écouteur (listener)
En générale c’est un composant qui lance un événement
(par exemple on clique un bouton)
Un écouteur exécute un programme spéciale (event handler)
à la suite d’un événement
3
Exception
•
•
•
Une exception est un événement
si une exception est lancée, l’événement s’est
produit
l’écouteur est le bloc catch
4
Object
Component
BorderLayout
FlowLayout
GridLayout
Container
java.awt
Window
Frame
JFrame
JComponent
javax.swing
AbstractClass
5
JComponent
JFrame
JMenuBar
JPanel
JLabel
AbstractButton
JMenuItem
JTextComponent
JButton
JTextArea
JMenu
JTextField
6
Les classes qui définissent des composants graphiques hérite de la
classe JComponent qui hérite de la classe Container
JButton: un bouton avec un libellé
JCheckBox: une case à cocher
JComboBox : une liste déroulante
JLabel: affichage d’un texte court
JList: composants permettant de sélectionner une ou plusieurs valeurs
JRadioButton:des buttons à choix exclusif
JScrollBar: barres de défilement
JScrollPane:
JTextComponent:
JTextArea:zone de texte plusieurs lignes
JTextField:zone de texte une ligne
JFrame : fenêtre
JPanel définition des zones graphiques où on place divers composants
graphiques
7
Classe Container
La classe Container ou ses classes descendantes peuvent contenir des
composants
par exemple JFrame et JPanel
Une interface graphique est composée en général
•d’un conteneur (Container) (JFrame ou JPanel)
•des composants inclus à ce conteneur (JButton, JLabel, etc.)
•la disposition des composants à l’intérieure du conteneur (Container)
(GridLayout,BorderLayout, FlowLayout)
8
import javax.swing.JFrame;
public class FirstWindow {
public static void main(String[] args)
{JFrame f1=new JFrame();
f1.setTitle("FirstWindow");
f1.setVisible(true);f1.setSize(300,200);
}}
ou
import javax.swing.JFrame;
public static final int WIDTHFenetre = 300;
public static final int HEIGHTFenetre = 200;
public class FirstWindow extends JFrame
{public FirstWindow( )
{ setSize(WIDTH, HEIGHT);
setTitle("First Window Class");
setVisible(true);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
public static void main(String[] args)
{FirstWindow f1=new FirstWindow();
}}
9
Classe Color
La classe Color est dans le package awt
Il y a des constantes pour des couleurs de base
Copyright © 2008 Pearson Addison-Wesley. All rights reserved
10
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Color;
class ColoredWindow extends JFrame
{
public static final int WIDTH = 300;
public static final int HEIGHT = 200;
public ColoredWindow(Color theColor)
{
super("No Charge for Color" );
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane( ).setBackground(theColor);
JLabel aLabel = new JLabel("Close-window button works.");
add(aLabel);
}
public ColoredWindow( )
{ this(Color.PINK);}
}
public class DemoColoredWindow
{public static void main(String[] args)
{
ColoredWindow w1 = new ColoredWindow( );
w1.setVisible(true);
ColoredWindow w2 = new ColoredWindow(Color.YELLOW);
w2.setVisible(true);
}
}
11
Copyright © 2008 Pearson Addison-Wesley. All rights reserved
12
Les composants sont disposés en fonction de
BorderLayout
Layout
GridLayout
méthode setLayout
setLayout (new BorderLayout())
ou
BorderLayout g=new BorderLayout();
setLayout(g);
13
Copyright © 2008 Pearson Addison-Wesley. All rights reserved
14
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.BorderLayout;
class BorderLayoutJFrame extends JFrame
{
public static final int WIDTH = 500;
public static final int HEIGHT = 400;
public BorderLayoutJFrame( )
{
super("BorderLayout Demonstration" );
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout( ));
JLabel label1 = new JLabel("First label");
add(label1, BorderLayout.NORTH);
JLabel label2 = new JLabel("Second label");
add(label2, BorderLayout.SOUTH);
JLabel label3 = new JLabel("Third label");
add(label3, BorderLayout.CENTER);
}
}
public class BorderLayoutDemo
{
public static void main(String[] args)
{
BorderLayoutJFrame gui = new BorderLayoutJFrame( );
gui.setVisible(true);
}
}
15
FlowLayout insère les composants l’un après l’autre
de gauche à droite
setLayout(new FlowLayout());
setLayout(new FlowLayout(FlowLayout.RIGHT);
GridLayout gère comme un tableau à 2 dimensions
setLayout(new GridLayout(rows, columns));
méthode add a un seul argument
add(label)
les composants sont ajoutés en commençant par la première ligne
et de gauche à droite
16
PANELS
Un panel est un objet de classe JPanel qui est un conteneur
(container)
•pour regrouper des petits objets dans un panel
•diviser un JFrame ou un autre conteneur (Container)
setLayout(new BorderLayout());
JPanel autrePanel = new JPanel();
autrePanel.setLayout(new FlowLayout());
•il n’est pas nécessaire d’utiliser la méthode getContentPane
comme pour JFrame
17
import
import
import
import
import
import
import
import
import
javax.swing.JFrame;
javax.swing.JPanel;
java.awt.BorderLayout;
java.awt.GridLayout;
java.awt.FlowLayout;
java.awt.Color;
javax.swing.JButton;
java.awt.event.ActionListener;
java.awt.event.ActionEvent;
public class PanelDemo extends JFrame implements ActionListener
{
public static final int WIDTH = 300;
public static final int HEIGHT = 200;
private JPanel redPanel,whitePanel,bluePanel;
public PanelDemo( )
{
super("Panel Demonstration"); setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout( ));
JPanel biggerPanel = new JPanel( );
biggerPanel.setLayout(new GridLayout(1, 3));
redPanel = new JPanel( );
redPanel.setBackground(Color.LIGHT_GRAY);
biggerPanel.add(redPanel);
whitePanel = new JPanel( ); whitePanel.setBackground(Color.LIGHT_GRAY);
biggerPanel.add(whitePanel);
bluePanel = new JPanel( );
bluePanel.setBackground(Color.LIGHT_GRAY);
biggerPanel.add(bluePanel);
add(biggerPanel, BorderLayout.CENTER);
18
JPanel buttonPanel = new JPanel( );
buttonPanel.setBackground(Color.LIGHT_GRAY);
buttonPanel.setLayout(new FlowLayout( ));
JButton redButton = new JButton("Red");
redButton.setBackground(Color.RED);
redButton.addActionListener(this);
buttonPanel.add(redButton);
JButton whiteButton = new JButton("White");
whiteButton.setBackground(Color.WHITE);
whiteButton.addActionListener(this);
buttonPanel.add(whiteButton);
JButton blueButton = new JButton("Blue");
blueButton.setBackground(Color.BLUE);
blueButton.addActionListener(this);
buttonPanel.add(blueButton);
add(buttonPanel, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e)
{
String buttonString = e.getActionCommand( );
if (buttonString.equals("Red")) redPanel.setBackground(Color.RED);
else if (buttonString.equals("White") whitePanel.setBackground(Color.WHITE);
else if (buttonString.equals("Blue"))bluePanel.setBackground(Color.BLUE);
else System.out.println("Unexpected error.");}
public static void main(String[] args)
{PanelDemo gui = new PanelDemo( );
gui.setVisible(true);}
}
19
interface ActionListener
défini dans java.awt.event.ActionListener
public interface ActionListener extends
EventListener{
public void actionPerformed(ActionEvent e)
{}
}
On inscrit un tel écouter auprès d’un composant
composant.addActionListener(ecouteur)
On précise ainsi que ecouter est intéressé par les événements
ActionEvent provoqués par le composant
20
JButton et JMenuItem sont dérivés de la classe abstraite
AbstractButton
•Lorsque que l’on clique sur un Button ou MenuItem,
un événement e se produit
•e devient un argument de la méthode actionPerformed
•un ou plusieurs écouteurs d’action réagiront à cet événement
JButton nextButton = new JButton("Next");
nextButton.setActionCommand("Next Button");
JMenuItem choose = new JMenuItem("Next");
choose.setActionCommand("Next Menu Item");
(par défaut c’est Next pour les 2, on utilise setActionCommand
pour les distinguer
21
Copyright © 2008 Pearson Addison-Wesley. All rights
reserved
22
17-22
Copyright © 2008 Pearson Addison-Wesley. All rights
reserved
23
17-23
Copyright © 2008 Pearson Addison-Wesley. All rights
reserved
24
17-24
JTextField et JTextArea sont des classes dérivées
de la classe abstraite JTextComponent
Copyright © 2008 Pearson Addison-Wesley. All rights
reserved
25
17-25
import
import
import
import
import
import
import
import
import
javax.swing.JFrame;
javax.swing.JPanel;
java.awt.GridLayout;
java.awt.Color;
javax.swing.JMenu;
javax.swing.JMenuItem;
javax.swing.JMenuBar;
java.awt.event.ActionListener;
java.awt.event.ActionEvent;
public class InnerListenersDemo extends JFrame
{
public static final int WIDTH = 300;
public static final int HEIGHT = 200;
private JPanel redPanel,whitePanel,bluePanel;
private class RedListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{ redPanel.setBackground(Color.RED);}
} //End of RedListener inner class
private class WhiteListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{whitePanel.setBackground(Color.WHITE); }
} //End of WhiteListener inner class
private class BlueListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{ bluePanel.setBackground(Color.BLUE);}
} //End of BlueListener inner class
26
public static void main(String[] args)
{
InnerListenersDemo gui = new InnerListenersDemo( );
gui.setVisible(true); }
public InnerListenersDemo( )
{
super("Menu Demonstration");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(1, 3));
redPanel = new JPanel( );redPanel.setBackground(Color.LIGHT_GRAY);
add(redPanel);
whitePanel = new JPanel();whitePanel.setBackground(Color.LIGHT_GRAY);
add(whitePanel);
bluePanel = new JPanel( );bluePanel.setBackground(Color.LIGHT_GRAY);
add(bluePanel);
JMenu colorMenu = new JMenu("Add Colors");
JMenuItem redChoice = new JMenuItem("Red");
redChoice.addActionListener(new RedListener( ));
colorMenu.add(redChoice);
JMenuItem whiteChoice = new JMenuItem("White");
whiteChoice.addActionListener(new WhiteListener( ));
colorMenu.add(whiteChoice);
JMenuItem blueChoice = new JMenuItem("Blue");
blueChoice.addActionListener(new BlueListener( ));
colorMenu.add(blueChoice);
}
}
JMenuBar bar = new JMenuBar( );bar.add(colorMenu);setJMenuBar(bar);
27
Ecouter de Souris
import java.awt.event.*;
import javax.swing.*;
class Fenetre extends JFrame implements MouseListener
{private JTextField champSaisie, champResultat;
private JButton b_calcul, b_quitter;
public Fenetre()
{setTitle("Gestion de clics");
setBounds (500,20,70,200);
addMouseListener(this); // son propre écouteur
}
public void mousePressed (MouseEvent ev)
{System.out.println("appui en "+ ev.getX() + " "+ ev.getY());}
public void mouseReleased (MouseEvent ev)
{System.out.println("relachement "+ ev.getX() + " "+ ev.getY());}
public void mouseClicked(MouseEvent ev) {}
public void mouseEntered(MouseEvent ev) {}
public void mouseExited(MouseEvent ev){}}
public class Sourisbis
{ public static void main (String[] args)
{Fenetre f1=new Fenetre();
f1.setSize(400,140); f1.setVisible(true);}
}
28
//Exercice pris du livre de R. Chevallier, Java 5
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Poly{
protected double[] coef;
protected int degre;
protected double x, res;
public Poly() {coef=new double[10];}
public void eval()
{res=0;
for (int i=0; i<10;i++)res= res+coef[i]*Math.pow(x,i);}}
class Fenetre extends JFrame implements ActionListener{
private JTextField[] casecoef;
private JTextField casedeg, casex, caseres;
private JButton calcul;
private Poly p;
public Fenetre(Poly pp)
{setTitle("POLYNOME");
Container cf= this.getContentPane()
JPanel p1=new JPanel();
p1.add(new JLabel("COEFFICIENTS"));
casecoef= new JTextField[10];
for (int i=0; i<10;i++)
{casecoef[i]=new JTextField(3);
p1.add(casecoef[i]);}
cf.add("North",p1);
29
JPanel p2=new JPanel();
p2.add(new JLabel("DEGRE: "));
casedeg=new JTextField(3);
p2.add(casedeg);
p2.add(new JLabel("Valeur de x: "));
casex=new JTextField(3);
p2.add(casex);
cf.add("Center",p2);
JPanel p3=new JPanel();
calcul=new JButton("CALCUL");
calcul.addActionListener(this);
p3.add(calcul);
p3.add(new JLabel("Resultat :"));
caseres=new JTextField(8);
p3.add(caseres);
cf.add("South",p3);
p=pp;}
public void actionPerformed (ActionEvent e){
p.degre=Integer.parseInt(casedeg.getText());
p.x=Double.parseDouble(casex.getText());
for (int i=0; i<=p.degre; i++)
p.coef[i]=Double.parseDouble(casecoef[i].getText());
p.eval();
caseres.setText(Double.toString(p.res));}
}//fin de fenetre
public class Exercice3
{ public static void main (String[] args)
{Poly p1=new Poly();
Fenetre f1=new Fenetre(p1);
f1.pack();f1.setVisible(true);}
}
30
Téléchargement