Vous êtes sur la page 1sur 10

Université Ibn Zohr

Faculté des Sciences


Filière : SMI& LP2I
Module : IHM /Java avancé

Serie N°1 IHM

Note !! API utilisé dans cette serie est swing


Exercice 1
Pour des questions de santé On recommande que la nourriture que vous mangez ait moins de 30% de ses
calories totales provenant de la graisse. Développez une application avec interface graphique qui calcule le
pourcentage de calories qui proviennent de graisse, pour cela il faut savoir le nombre de grammes de graisse et le
nombre des calories provenant de la nourriture utilisée. Sachant que La graisse contient 9 calories par gramme.
Entrée :
⮚ Calories servit dans la nourriture

⮚ Quantité de graisse servit.


Calcule : percent = ( (fat * 9) / calories ) * 100
Sortie : Pourcentage de calorie provenant de la graisse.
Combien de composant qui seront utilisées dansGUI?
Quelles seront les composants reliées au listener?
Ecrire un programme implémentant une interface de la figure dessous
Démarche
1- Suggérez une disposition des panneaux pour
créer cet interface de l'utilisateur
2- Ecrire un programme Java réalisant cet interface

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

public class percentFat extends JFrame implements ActionListener


{
JLabel title = new JLabel("Percent of Calories from Fat");
JLabel fatLabel = new JLabel("Enter grams of fat: ");
JLabel calLabel = new JLabel("Enter total calories: ");
JLabel perLabel = new JLabel("Percent calories from fat: ");

JTextField inFat = new JTextField( 7 );


JTextField inCal = new JTextField( 7 );
JTextField outPer = new JTextField( 7 );

JButton doit = new JButton("Do It!");

int calories ; // input: total calories per serving


int fatGrams ; // input: grams of fat per serving
double percent; // result: percent of calories from fat

public percentFat()
{
setTitle( "Calories from Fat" );
getContentPane().setLayout( new FlowLayout() );

getContentPane().add( title );
getContentPane().add( fatLabel );
getContentPane().add( inFat );
getContentPane().add( calLabel );
getContentPane().add( inCal );
getContentPane().add( perLabel );
getContentPane().add( outPer );
outPer.setEditable( false );

getContentPane().add( doit );
doit.addActionListener( this );
}

// The application
public void calcPercent( )
{
percent = ( (fatGrams * 9.0) / calories ) * 100.0 ;
}

public void actionPerformed( ActionEvent evt)


{
String userIn ;
userIn = inFat.getText() ;
fatGrams = Integer.parseInt( userIn ) ;

userIn = inCal.getText() ;
calories = Integer.parseInt( userIn ) ;

calcPercent() ;

outPer.setText( (percent+" ").substring(0,6) );


repaint();
}

public static void main ( String[] args )


{
percentFat fatApp = new percentFat() ;

WindowQuitter wquit = new WindowQuitter();


fatApp.addWindowListener( wquit );
fatApp.setSize( 280, 200 );
fatApp.setVisible( true );
}
}

class WindowQuitter extends WindowAdapter


{
public void windowClosing( WindowEvent e )
{ System.exit( 0 ); }
}

Exercice 2
Soit une application qui calcule le poids idéal d'une personne (en pounds) à partir de son genre et sa
hauteur (en pouces).L'interface graphique utilise des boutons radio. Le code suivants montre comment
créer un groupe bouton et comment lui intégré les boutons radio ainsi créer.
Les boutons radio produisent des événements, comme le font les boutons normaux. Une application complète
exige un listener pour réponde aux actions sur les boutons radios. Pour cela il faut utilisez le méthode
setActionCommand () pour assigner une commande à chaque bouton radio, et la méthode getActionCommand ()
dans listener pour déterminer quel bouton a été activé.

2
1- Combien de groupes bouton sont utilisés dans cet
interface graphique?
2- Ecrire un programme Java réalisant cette interface
3- Utilisez la stratégie d’emplacements de
BorderLayout suivante pour réliser l’interface

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class IdealWeight extends JFrame implements ActionListener
{
JLabel lbl1;
JLabel lbl2;
JLabel lbl3;
JRadioButton rbm;//radio button male
JRadioButton rbf;
JRadioButton rbh1;//radio button height 1
JRadioButton rbh2;
JRadioButton rbh3;
JRadioButton rbh4;
JRadioButton rbh5;
JTextField outw;//out weight
ButtonGroup gender;
ButtonGroup height;
JPanel genpanel;
JPanel hpanel;
JPanel wpanel;

public IdealWeight()
{

lbl1 = new JLabel ( "Your Gender" );


rbm = new JRadioButton("Male",true) ;
rbf = new JRadioButton("Female",false);
gender = new ButtonGroup();
lbl2 = new JLabel ( "Your Height" );
rbh1 = new JRadioButton("60 to 64 inches",true) ;
rbh2 = new JRadioButton("64 to 68 inches",false) ;
rbh3 = new JRadioButton("68 to 72 inches",false) ;
rbh4 = new JRadioButton("72 to 76 inches",false) ;
rbh5 = new JRadioButton("76 to 80 inches",false) ;
height = new ButtonGroup();
lbl3 = new JLabel ( "Ideal Weight" );
outw = new JTextField (15);
JPanel genpanel = new JPanel();
JPanel hPanel = new JPanel();
JPanel wPanel = new JPanel();
rbf.addActionListener( this );
rbm.addActionListener( this );
rbh1.addActionListener( this );
rbh2.addActionListener( this );
rbh3.addActionListener( this );
rbh4.addActionListener( this );
rbh5.addActionListener( this );
rbm.setActionCommand("m");
rbf.setActionCommand("f");
rbh1.setActionCommand("h1");
rbh2.setActionCommand("h2");
rbh3.setActionCommand("h3");

3
rbh4.setActionCommand("h4");
rbh5.setActionCommand("h5");

getContentPane().setLayout( new BorderLayout() );

gender.add(rbm);
gender.add(rbf);
genpanel.add(lbl1);
genpanel.add(rbm);
genpanel.add(rbf);
hPanel.add(lbl2);
height.add(rbh1);
height.add(rbh2);
height.add(rbh3);
height.add(rbh4);
height.add(rbh5);
hPanel.add(rbh1);
hPanel.add(rbh2);
hPanel.add(rbh3);
hPanel.add(rbh4);
hPanel.add(rbh5);
wPanel.add(lbl3);
wPanel.add(outw);
getContentPane().add( genpanel, BorderLayout.WEST );
getContentPane().add( hPanel, BorderLayout.EAST );
getContentPane().add( wPanel, BorderLayout.SOUTH );

genpanel.setLayout(
new BoxLayout( genpanel, BoxLayout.Y_AXIS ) );
hPanel.setLayout(
new BoxLayout( hPanel, BoxLayout.Y_AXIS ) );
outw.setEditable(false);
}
public void actionPerformed( ActionEvent evt)
{ int h=0;
double w=0;
//height.getSelection().getActionCommand();
if(height.getSelection().getActionCommand().equals("h1"))
h=60;
if(height.getSelection().getActionCommand().equals("h2"))
h=64;
if(height.getSelection().getActionCommand().equals("h3"))
h=68;
if(height.getSelection().getActionCommand().equals("h4"))
h=72;
if(height.getSelection().getActionCommand().equals("h5"))
h=76;
//gender.getSelection().getActionCommand();
if(gender.getSelection().getActionCommand().equals("m"))
w=(h*h)/30.0;
if(gender.getSelection().getActionCommand().equals("f"))
w=(h*h)/28.0;

outw.setText(" "+w);
repaint();
}
public static void main ( String[] args )
{ IdealWeight frm = new IdealWeight();
WindowQuitter wquit = new WindowQuitter();
frm.addWindowListener( wquit );
frm.setSize( 350, 200 );
frm.setResizable(false);//pour ne pa redimensionner la fenêtre
frm.setVisible( true ); }
}
class WindowQuitter extends WindowAdapter
{ public void windowClosing( WindowEvent e )
{ System.exit( 0 ); }}

4
}
Exercice 4
On souhaite Ecrire un programme Java effectuant la conversion le dirhams en diverses devise : Dollars, Franc
Swiss, Franc Belge, Peseta Espagnol et en Euro. L’interface de cette application est présentée dans la figure 1

Figure 1 Figure2

Sachant qu’
Un Dollar 10 dirhams
Un franc Français 1.50 dirhams
Un franc Belge
Un franc Swiss
10 Peseta Espagnol
Tableau 1
1- Ecrire une méthode convert() permettant de convertir le dirhams en divers devises du tableau 1 ;
2- Combien de composant contenus dans cette fenêtre de la figure 1.
3- Lesquelles seront reliées à un listener?
4- Ecrire le programme java réalisant l’interface de la figure 1 et qui convertit le dirham en diverses
devises
L’interface de la figure1 présente un sérieux problème. Lorsque l’utilisateur redimensionne la fenêtre les
composantes ne reste pas appariés et changent de place (voir figure2). On peut empêcher l’utilisateur de
redimensionner la fenêtre en utilisant la méthode : frm.setResizable(false), comme on peut aussi utiliser des
gestionnaires d’agacement et des panneaux.
5- Proposez une solution basée sur l’utilisation des panneaux (Panel) et les gestionnaires d’agacement pour
réaliser l’interface figure3

5
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Conversion extends JFrame implements ActionListener
{
JLabel lbl1,lbl2;

int h;
double r;
JRadioButton rbh1;//radio button height 1
JRadioButton rbh2;
JRadioButton rbh3;
JRadioButton rbh4;
JRadioButton rbh5;
JTextField out_data,In_data;//out weight
ButtonGroup monaie;

JPanel monaiepanel;
JPanel wpanel,hpanel;

public Conversion()
{

lbl1 = new JLabel ( "Donnez la valeur en DIRHAMS" );


monaie = new ButtonGroup();
rbh1 = new JRadioButton("Francs",true) ;
rbh2 = new JRadioButton("Dollars",false) ;
rbh3 = new JRadioButton("Francs Swiss ",false) ;
rbh4 = new JRadioButton("Francs Belge",false) ;
rbh5 = new JRadioButton("Livre Stirlling",false) ;
lbl2 = new JLabel ( "Monaie Convertit en Euro" );
out_data = new JTextField (15);
In_data = new JTextField (15);
JPanel hpanel = new JPanel();
JPanel monaiepanel = new JPanel();
JPanel wpanel = new JPanel();
rbh1.addActionListener( this );
rbh2.addActionListener( this );
rbh3.addActionListener( this );
rbh4.addActionListener( this );
rbh5.addActionListener( this );
rbh1.setActionCommand("h1");
rbh2.setActionCommand("h2");
rbh3.setActionCommand("h3");
rbh4.setActionCommand("h4");
rbh5.setActionCommand("h5");

getContentPane().setLayout( new FlowLayout() );


// getContentPane().setLayout( new BorderLayout() );

hpanel.add(lbl1);
hpanel.add(In_data);
monaie.add(rbh1);
monaie.add(rbh2);
monaie.add(rbh3);
monaie.add(rbh4);
monaie.add(rbh5);

6
monaiepanel.add(rbh1);
monaiepanel.add(rbh2);
monaiepanel.add(rbh3);
monaiepanel.add(rbh4);
monaiepanel.add(rbh5);

wpanel.add(lbl2);
wpanel.add(out_data);

getContentPane().add( hpanel);
getContentPane().add( monaiepanel);
getContentPane().add( wpanel);

/*monaiepanel.setLayout(
new BoxLayout( monaiepanel, BoxLayout.Y_AXIS ) );
hpanel.setLayout(
new BoxLayout( hpanel, BoxLayout.X_AXIS ) );
wpanel.setLayout(
new BoxLayout( wpanel, BoxLayout.X_AXIS ) );
getContentPane().add( hpanel, BorderLayout.NORTH );
getContentPane().add( monaiepanel, BorderLayout.CENTER);
getContentPane().add( wpanel, BorderLayout.SOUTH );*/
out_data.setEditable(false);
}
public void convert(char d )
{ switch (d)
{case '1': r = (h / 10.0);break;
case '2': r = (h / 8.20);break;
case '3': r = (h / 12.0);break;
case '4': r = (h / 9.0);break;
case '5': r = (h / 3.0);break;
}

}
public void actionPerformed( ActionEvent evt)
{
String userIn = In_data.getText();
h=Integer.parseInt( userIn );
if(monaie.getSelection().getActionCommand().equals("h1"))
convert('1');
if(monaie.getSelection().getActionCommand().equals("h2"))
convert('2');
if(monaie.getSelection().getActionCommand().equals("h3"))
convert('3');
if(monaie.getSelection().getActionCommand().equals("h4"))
convert('4');
if(monaie.getSelection().getActionCommand().equals("h5"))
convert('5');
out_data.setText(" "+r);
repaint();
}
public static void main ( String[] args )
{ Conversion frm = new Conversion();
WindowQuitter wquit = new WindowQuitter();
frm.addWindowListener( wquit );
frm.setSize( 350, 200 );

7
frm.setResizable(true);//pour ne pa redimensionner la fenêtre
frm.setVisible( true ); }
}
class WindowQuitter extends WindowAdapter
{ public void windowClosing( WindowEvent e )
{ System.exit( 0 ); }}
Exercise4:
1- Suggérez une disposition
des panneaux pour créer
cet interface de l'utilisateur
2- Ecrire un programme
Java réalisant cet interface

import java.awt.*;
import java.awt.event.*;
class FArticle extends Frame implements ActionListener{
private Panel p1,p2,p3,p4;
private TextField tfNom,tfPrixhtaxe,tfPrixTTC, tfReference,tfTauxTva;
private Label lNom,lPrixhtaxe,lReference, lTauxTva,lPrixTTC;
private TextArea taCouleur;
private Button btCreate;
private Button cmdExit ;
public FArticle(String s){
super(s);
addWindowListener(new clExit());
p1=new Panel(new FlowLayout(FlowLayout.CENTER));
p3=new Panel(new FlowLayout(FlowLayout.CENTER));
p4=new Panel(new FlowLayout(FlowLayout.CENTER));
p2=new Panel(new BorderLayout());
lReference=new Label("Reference");
tfReference=new TextField(5);
lNom=new Label("Article");
tfNom=new TextField(5);
lPrixhtaxe=new Label("Prix hors Taxe");
tfPrixhtaxe=new TextField(5);
lTauxTva=new Label("Taux TVA");
tfTauxTva=new TextField(5);
lPrixTTC=new Label("Prix TTC");
tfPrixTTC=new TextField(5);
taCouleur=new TextArea ("Information sur l'Article : ", 14,
50,TextArea.SCROLLBARS_BOTH);
btCreate=new Button("Create");
btCreate.addActionListener(this);
cmdExit = new Button(" Quitter ");
cmdExit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QuitterActionPerformed(evt); } });
tfTauxTva.setText("19.6");
p1.add(lNom);
p1.add(tfNom);
p1.add(lReference);
p1.add( tfReference);
p1.add(lPrixhtaxe);

8
p1.add(tfPrixhtaxe);
p1.add( lTauxTva);
p1.add(tfTauxTva);
p1.add(lPrixTTC);
p1.add( tfPrixTTC);
p3.add(taCouleur);
p4.add(btCreate);
p4.add(cmdExit );
p2.add(BorderLayout.NORTH,p1);
p2.add(BorderLayout.CENTER,p3);
p2.add(BorderLayout.SOUTH,p4);
p2.setBackground(Color.getHSBColor(97,231,120));
p1.setBackground(Color.getHSBColor(157,0,120));
p4.setBackground(Color.getHSBColor(150,240,13));
add(p2);
setSize(700,300);
setVisible(true);
}

public void actionPerformed(ActionEvent e){

if(e.getSource()==(btCreate)){

String valueHT = tfPrixhtaxe.getText();


double price = Double.valueOf(valueHT).doubleValue();

String TauxTVA = tfTauxTva.getText();


double rate = Double.valueOf(TauxTVA).doubleValue();

price = price + (price/100) * rate;


tfPrixTTC.setText("" + price);

String s=new String();


s+=" Nom Article : "+ tfNom.getText()+"\n"+"Reference Article :
"+tfReference.getText()+"\n"+"Prix unitaire Hors Taxe : "+tfPrixhtaxe.getText()+"\n";
s+="Prix TTC "+tfPrixTTC.getText()+"\n";;
taCouleur.setText(s);
tfNom.setText("");
tfPrixhtaxe.setText("");
tfReference.setText("");
}

}
private void QuitterActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
public static void main(String[] arg){
FArticle F=new FArticle("Fenetre");

}
Exercise5

1- Ecrire un programme Java réalisant cet interface


en utilisant Menu

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

import java.awt.*;

public class MenuDemo extends JFrame {

public MenuDemo () {
super();
setTitle(" Titre de la Fenetre ");
setSize(300, 150);

MenuBar mb = new MenuBar();


setMenuBar(mb);

Menu m = new Menu(" un menu ");


mb.add(m);
m.add(new MenuItem(" 1er element "));
m.add(new MenuItem(" 2eme element "));
Menu m2 = new Menu(" sous menu ");
CheckboxMenuItem cbm1 = new CheckboxMenuItem(" menu item 1.3.1 ");
m2.add(cbm1);
cbm1.setState(true);
CheckboxMenuItem cbm2 = new CheckboxMenuItem(" menu item 1.3.2 ");
m2.add(cbm2);

m.add(m2);
pack();
show();
}
public static void main(String[] args) {
teste frm=new teste();
frm.setSize( 350, 250 );
frm.setResizable(false);
frm.setVisible( true );
// affiche la fenetre
}}

10

Vous aimerez peut-être aussi