0% found this document useful (0 votes)
43 views

Solution TD Java 4-8

The document contains examples of Java code implementing various GUI and exception handling concepts: 1) It defines classes for bank accounts, shapes, employees, and cities that throw custom exceptions under certain conditions. 2) It shows how to create GUI windows that listen for mouse events using interfaces and inner classes. Events like clicks and releases are printed. 3) It demonstrates try/catch blocks to handle potential exceptions from input validation and arithmetic operations. Finally blocks are used to ensure code runs after exceptions.

Uploaded by

draou maissa
Copyright
© © All Rights Reserved
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

Solution TD Java 4-8

The document contains examples of Java code implementing various GUI and exception handling concepts: 1) It defines classes for bank accounts, shapes, employees, and cities that throw custom exceptions under certain conditions. 2) It shows how to create GUI windows that listen for mouse events using interfaces and inner classes. Events like clicks and releases are printed. 3) It demonstrates try/catch blocks to handle potential exceptions from input validation and arithmetic operations. Finally blocks are used to ensure code runs after exceptions.

Uploaded by

draou maissa
Copyright
© © All Rights Reserved
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 30

TD N4:

//exo1

public class banque {

private int Ncompte;

private double solde;

private String CIN;

public banque(int Ncompte,double solde,String CIN){

this.Ncompte=Ncompte;

this.solde=solde;

this.CIN=CIN;

public void deposer(double somme){

solde+=somme;

public void retirer (double somme){

if(solde>=somme){

solde=solde-somme;

else {

System.out.println(" Retrait impossible");}

public double avoirSolde(){


return solde;

public String avoirInf(){

return ("Ncompte"+Ncompte+" CIN "+CIN);

public static void main(String[] args) {

banque compte= new banque(1, 5000.75, "AB1200");

System.out.println(compte.avoirInf());

System.out.println(compte.avoirSolde());

compte.deposer(500);

System.out.println(compte.avoirInf());

compte.retirer(200);

System.out.println(compte.avoirInf());

System.out.println(compte.avoirSolde());

//exo3

abstract class figure_2pts{

protected double xa,ya,xb,yb;

abstract void calcul_perimetre();

abstract void calcul_surface();

public figure_2pts(double xxa,double yya,double xxb,double yyb){

xa = xxa;

ya = yya;
xb = xxb;

yb = yyb;

public void affiche(){

System.out.println("point a = "+xa+""+ya+"point b = "+xb+""+yb);}

class rectangle extends figure_2pts {

private double l1,l2;

public rectangle(double xxa, double yya, double xxb, double yyb) {

super(xxa, yya, xxb, yyb);

l1 =Math.abs(xb-xa);

l2 =Math.abs(xb-xa);}

public void calcul_perimetre(){

double per=l1*2+l2*2;

System.out.println("le perimetre de rectengle est: "+per);

public void calcul_surface(){

double surf=l1*l2;

System.out.println("la surface de rectengle est: "+surf);}

public static void main(String[] args) {

rectangle rct=new rectangle(2, 01, 03, 03);

rct.calcul_perimetre();

rct.calcul_surface();

rct.affiche(); }}

//exo5

class Pers_admin implements itf_calcul {


private String nom,specialite;

private int age,indice;

private double prime;

public Pers_admin(String n,String s,int a,int i){

nom=n;

specialite=s;

age=a;

indice=i;

public void calcul_prime(){

prime=age*valeur[indice];

System.out.println("la prime est "+prime);

public void affiche(){

System.out.println("le nom est "+nom+",l'age: "+age+", la specialite est "+specialite);

}}

//exo5

public interface itf_calcul {

double[]valeur={33.2,13.2,5.8};

public void calcul_prime();

public class test5 {

public static void main(String[] args) {

Pers_admin p1=new Pers_admin("chaima", "RT", 20, 1);

p1.calcul_prime();
p1.affiche();}}

TD N5:
//ex1:

public class exo1{

public static void main(String[] args) {

try{

int x=10/0;

System.out.println("x="+x);}

catch(Exception e){

System.out.println("Exception"+e);

e.printStackTrace();

int x=10/1;

System.out.println("x="+x);

System.out.println("fin de main");}

}}

//exo2 1

public class EntNat{

private int n;

public EntNat (int n) throws ErrConst{

if(n<0) throw new ErrConst(null);

this.n=n;

public int getN(){

return n;

}}
// ex2 2

class ErrConst extends Exception{

public ErrConst(String String){ }}

//exo2 3

public class test_EntNat{

public static void main(String[] args) {

try{

EntNat n1=new EntNat(5);

System.out.println("n="+n1.getN());

EntNat n2=new EntNat(-7);

System.out.println("n="+n2.getN());

catch(ErrConst e){

System.out.println("Erreur construction ");}}}

//exo3 1

public class ville {

private String nomVille,nomPays;

private int nbrHabitants;

private char categorie;

public ville(String pNom,int pNbr,String pPays) throws ErrCons{

if(pNbr<0) throw new ErrCons("Vous avez donne un nombre negatif");

System.out.println("Creation d'une ville avec des parametres!");

nomVille=pNom;

nbrHabitants=pNbr;
nomPays=pPays;

this.setCategorie();

public void setNombreHabitants(int nbre) throws ErrCons{

if(nbre<0) throw new ErrCons("Vous avez donne un nombre negatif");

nbrHabitants=nbre;

this.setCategorie();

//definir la categorie de la ville

private void setCategorie(){

int borneSup[]={0,1000,10000,100000,500000,1000000,5000000,10000000};

char categorie[]={'?','A','B','C','D','E','F','G','H'};

int i=0;

while(i<borneSup.length && this.nbrHabitants >= borneSup[i])

i++;

this.categorie = categorie[i];}

public String affiche(){

return "\t"+this.nomVille+" est une ville de "+this.nomPays+" ,elle comporte :"

+this.nbrHabitants+" habitants => elle est donc de categorie :"+this.categorie;

class ErrCons extends Exception{

ErrCons(String msg)

{super(msg);}

public static void main(String[] args) {


try{

ville v1=new ville("oran", 10, "algerie");

v1.setNombreHabitants(-2000);

catch (ErrCons e){

System.out.println(e.getMessage()); }}}

(JE N'AI PAS LA SUITE)

//exo4

public class finall{

//private static Exception now;

public static void f(int n){

try{

if(n!=1) throw new Except ();

catch(Except e){

System.out.println("catch dans f-n=" +n);

return;

finally{

System.out.println("dans finally-n= "+n);

public static void main(String[] args) {

f(1);

f(2);}}
//exo 4

public class Except extends Exception{}

TD N6:
//exo1

import javax.swing.*;

import java.awt.event.*;

public class MaFenetre extends JFrame implements MouseListener {

public MaFenetre(){

setTitle("Gestion de clics");

setBounds(20,20,400,200);

addMouseListener(this);

public void mouseClicked(MouseEvent ev){} // ki tcliki

public void mousePressed(MouseEvent ev){} // ki tcliki w tmchi

public void mouserReleased(MouseEvent ev){} // ki tdorki w ttlgui

public void mouseEntered(MouseEvent ev){}

public void mouseExited(MouseEvent ev){}

@Override // erreur dans class name???

public void mouseReleased(MouseEvent e) {

// TODO Auto-generated method stub

throw new UnsupportedOperationException("Unimplemented method 'mouseReleased'");

public static void main(String[] args) {

MaFenetre fen=new MaFenetre();

fen.setVisible(true);
}

//ex2

import javax.swing.*;

import java.awt.event.*;

public class exo2 extends JFrame implements MouseListener {

public exo2() {

setTitle("Gestion de clics");

setBounds(10,20,300,200);

addMouseListener(this);

public void mouseClicked(MouseEvent ev){}

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 mouseEntered(MouseEvent ev) {}

public void mouseExited(MouseEvent ev) {}

public static void main(String[] args) {

exo2 f=new exo2();

f.setVisible(true);

}}

//exo 2 partie 2
import javax.swing.*;

import java.awt.event.*;

public class exo22 extends JFrame {

public exo22() {

setTitle("Gestion de clics");

setBounds(10,20,300,200);

addMouseListener(new Ecouteur());

}}

class Ecouteur implements MouseListener{

public void mouseClicked(MouseEvent ev){}

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 mouseEntered(MouseEvent ev) {}

public void mouseExited(MouseEvent ev) {}

public static void main(String[] args) {

exo2 f=new exo2();

f.setVisible(true);

//ex3 partie 1 M1

import javax.swing.*;

import java.awt.event.*;
public class exo3 extends JFrame implements MouseListener{

private int num;

private static int nbFen=0;

public exo3(){

nbFen++;

num=nbFen;

setTitle("fenetre "+num);

setBounds(10,20,300,200);

addMouseListener(this);

public void mouseClicked(MouseEvent ev){}

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 mouseEntered(MouseEvent ev) {}

public void mouseExited(MouseEvent ev) {}

public static void main(String[] args) {

for(int i=1;i<5;i++){

exo3 f=new exo3();

f.setVisible(true);}}}

//exo3 p2

import javax.swing.*;

import java.awt.event.*;

public class exo3q2 extends JFrame {


int i;

public exo3q2(int i){

this.i=i;

setTitle("fenetre "+i);

setBounds(10,20,300,200);

addMouseListener(new ecout(i));}

class ecout extends MouseAdapter{

int i;

public ecout(int i){

this.i=i;}

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());

}}

//exo4

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class fen2boutons extends JFrame implements ActionListener{

public fen2boutons(){

setTitle("Avec deux boutons");

setSize(200,100);
monBouton1 = new JButton("B1");

monBouton2=new JButton("B2");

monBouton3=new JButton("B3");

Container contenu = getContentPane();

contenu.setLayout(new FlowLayout());//decposition des composentes dans la fenetre

contenu.add(monBouton1);

contenu.add(monBouton2);

contenu.add(monBouton3);

monBouton1.addActionListener(this);

monBouton2.addActionListener(this);

monBouton3.addActionListener(this);}

public void actionPerformed (ActionEvent ev) {

if(ev.getSource()==monBouton1)

System.out.println("action sur bouton B1 ");

if(ev.getSource()==monBouton2)

System.out.println("action sur bouton B2");

if(ev.getSource()==monBouton3)

System.out.println("action sur bouton B3 ");

public static void main(String[] args) {

fen2boutons fen=new fen2boutons();

fen.setVisible(true);

private JButton monBouton1, monBouton2 ,monBouton3; }

//exo5
import javax.swing.*;

import java.awt.event.*;

import java.util.Random;

import java.awt.*;

public class tirage extends JFrame implements ActionListener {

private JTextField t1,t2,t3,g;

private JButton t;

private JLabel r;

private JPanel p1,p2;

public tirage(){

setTitle("Jeu 3 nbrs");

setSize(350,150);

Container cn=getContentPane();

cn.setLayout(new FlowLayout());

//Creation du textF

p1=new JPanel();

cn.add(p1);

t1=new JTextField(6);

p1.add(t1);

t1.addActionListener(this);

t2=new JTextField(6);

p1.add(t2);

t2.addActionListener(this);

t3=new JTextField(6);
p1.add(t3);

t3.addActionListener(this);

// button et res

p2=new JPanel();

cn.add(p2);

t=new JButton("Tirage");

p2.add(t);

t.addActionListener(this);

r=new JLabel("Resultat");

p2.add(r);

g=new JTextField(10);

p2.add(g);

g.addActionListener(this);

public void actionPerformed(ActionEvent ev){

Object source=ev.getSource();

if(source==t){

Random rn=new Random();

int n1=rn.nextInt(10);

int n2=rn.nextInt(10);

int n3=rn.nextInt(10);

//2eme methode pour le Random

/*int n1=(int) (Math.random()*10);

int n2=(int) (Math.random()*10);

int n3=(int) (Math.random()*10);*/


t1.setText(Integer.toString(n1)); // pour afficher le nbr choisi par random dans le textF

t2.setText(Integer.toString(n2));

t3.setText(Integer.toString(n3));

int s=n1+n2+n3;

if(s>15) g.setText("GAGNE");

else g.setText("PERDU");

public static void main(String[] args) {

tirage ti=new tirage();

ti.setVisible(true);

TD N7:
//ex1

import javax.swing.* ;

import java.awt.* ;

import java.awt.event.* ;

public class ex1 extends JFrame implements ActionListener, ItemListener{

public ex1(){

setTitle ("Cases a cocher") ;

setSize (300, 140) ;

Container contenu = getContentPane () ;

// les deux boutons

boutRaz = new JButton ("RAZ") ;


boutRaz.addActionListener (this) ;

contenu.add (boutRaz, "North") ;

boutEtat = new JButton ("Etat") ;

boutEtat.addActionListener (this) ;

contenu.add (boutEtat, "South") ;

// les cases a cocher dans un panneau

pan = new JPanel () ;

contenu.add (pan) ;

cercle = new JCheckBox ("Cercle") ;

pan.add (cercle) ;

cercle.addActionListener (this) ;

cercle.addItemListener (this) ;

rectangle = new JCheckBox ("Rectangle") ;

pan.add (rectangle) ;

rectangle.addActionListener (this) ;

rectangle.addItemListener (this) ;

triangle = new JCheckBox ("Triangle") ;

pan.add (triangle) ;

triangle.addActionListener (this) ;

triangle.addItemListener (this) ;}

public void actionPerformed (ActionEvent e){

Object source = e.getSource() ;

if (source == boutRaz){

cercle.setSelected (false) ;

rectangle.setSelected (false) ;
triangle.setSelected (false) ;

if (source == boutEtat){

System.out.print ("Cases selectionnees : ") ;

if (cercle.isSelected()) System.out.print (" cercle ") ;

if (rectangle.isSelected()) System.out.print (" rectangle ") ;

if (triangle.isSelected()) System.out.print (" triangle ") ;

System.out.println() ;

if (source == cercle) System.out.println ("Action case cercle") ;

if (source == rectangle) System.out.println ("Action case rectangle") ;

if (source == triangle) System.out.println ("Action case triangle") ;}

public void itemStateChanged (ItemEvent e)

{ Object source = e.getSource() ;

if (source == cercle) System.out.println ("Item case cercle") ;

if (source == rectangle) System.out.println ("Item case rectangle") ;

if (source == triangle) System.out.println ("Item case triangle") ;

private JButton boutRaz, boutEtat ;

private JPanel pan ;

private JCheckBox cercle, rectangle, triangle ;

public static void main (String args[]){

ex1 fen = new ex1() ;

fen.setVisible(true) ;

}}
//ex2

import javax.swing.* ;

import java.awt.* ;

import java.awt.event.* ;

class ex2 extends JFrame implements ActionListener{

public ex2 (String[] libelles){

setTitle ("Boutons radio") ;

setSize (400, 160) ;

Container contenu = getContentPane () ;

boutEtat = new JButton ("Etat") ;

boutEtat.addActionListener (this) ;

contenu.add (boutEtat, "South") ;

pan = new JPanel () ;

contenu.add (pan) ;

this.libelles = libelles ;

nbBoutons = libelles.length ;

ButtonGroup groupe = new ButtonGroup() ;

boutons = new JRadioButton [nbBoutons] ;

for (int i=0 ; i<nbBoutons ; i++)

{ boutons[i] = new JRadioButton (libelles[i]) ;

pan.add (boutons[i]) ;

groupe.add (boutons[i]) ;

boutons[i].addActionListener (this) ;

if (nbBoutons > 0) boutons[0].setSelected(true) ;}


public void actionPerformed (ActionEvent e)

{ Object source = e.getSource() ;

if (source == boutEtat)

{ System.out.print ("Bouton selectionne = ") ;

for (int i=0 ; i<nbBoutons ; i++)

if (boutons[i].isSelected()) System.out.print (libelles[i]+ " ") ;

System.out.println() ;

for (int i=0 ; i<nbBoutons ; i++)

if (source == boutons[i])

System.out.println ("Action bouton " + libelles[i]) ;

private JButton boutEtat ;

private JPanel pan ;

private JRadioButton boutons[] ;

private String libelles[] ;

private int nbBoutons ;

public static void main (String args[]){

String libelles[] = {"Cercle", "Rectangle", "Triangle", "Pentagone",

"Ellipse", "Carre"} ;

ex2 fen = new ex2(libelles) ;

fen.setVisible(true) ;}}

//ex3

import java.awt.* ;

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

public class ex3 extends JFrame implements ActionListener {

public ex3 () {

setTitle ("Carres") ;

setSize (400, 100) ;

Container contenu = getContentPane() ;

contenu.setLayout (new FlowLayout() ) ;

labNombre = new JLabel (etiqNombre) ;

contenu.add(labNombre) ;

nombre = new JTextField (10) ;

contenu.add(nombre) ;

boutonCalcul = new JButton ("CALCUL") ;

contenu.add(boutonCalcul) ;

boutonCalcul.addActionListener(this) ;

labCarre = new JLabel (etiqCarre) ;

contenu.add(labCarre) ;

public void actionPerformed (ActionEvent e)

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

try

{ String texte = nombre.getText() ;

int n = Integer.parseInt(texte) ;

long carre = (long)n*(long)n ;

labCarre.setText (etiqCarre + carre) ;

}
catch (NumberFormatException ex)

{ nombre.setText ("") ;

labCarre.setText (etiqCarre) ;

private JLabel labNombre, labCarre ;

private JTextField nombre ;

static private String etiqNombre = "Nombre : ", etiqCarre = "Carre : " ;

private JButton boutonCalcul ;

public static void main (String args[])

{ ex3 fen = new ex3() ;

fen.setVisible(true) ;

TD N8:
//ex1

import javax.swing.JOptionPane;

public class ex1 {

public static void main(String[] args) {

int nombre = 2;

int reponse;

do {

double racineCarree = Math.sqrt(nombre);

JOptionPane.showMessageDialog(null, "La racine carrée de " + nombre + " est : " + racineCarree);

reponse = JOptionPane.showConfirmDialog(null, "Voulez-vous continuer ?", "Continuer ?",


JOptionPane.YES_NO_OPTION);

// Passer au prochain nombre pair

nombre += 2; }

while (reponse == JOptionPane.YES_OPTION);

}}

//ex2

import javax.swing.*;

public class exo2 {

public static void main(String[] args) {

double note;

int n=1;

boolean correct;

double somme=0;

double moy;

int reponse;

do{

n++;

do{

correct=false;

String txt=JOptionPane.showInputDialog(null,"Entrer la note"+n,"


notes",JOptionPane.INFORMATION_MESSAGE);

try{

note=Double.parseDouble(txt);

correct=true;

somme+=note;

}
catch(NumberFormatException e){

JOptionPane.showMessageDialog(null, "Note incorrecte");}

}while (!correct);

reponse=JOptionPane.showConfirmDialog(null,"Autre
notes","Confirmation",JOptionPane.YES_NO_OPTION);

}while(reponse==JOptionPane.YES_OPTION);

moy=somme/n;

JOptionPane.showMessageDialog(null, "La moyenne des "+n+" notes="+moy);

}}

//ex3

import java.io.*;

public class ex3 {

public static void main(String[] args) {

try {

int som=0;

FileReader fileReader = new FileReader("matrice.txt");

BufferedReader reader = new BufferedReader(fileReader);

while (reader.ready()) {

String[] line = reader.readLine().split(" ");

for (String s : line) {

System.out.print(s+" ");

som+=Integer.parseInt(s);

System.out.println();

}
System.out.println("somme= "+som);

reader.close();

fileReader.close();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

//ex4

import java.io.FileNotFoundException;

import java.io.FileWriter;

import java.io.IOException;

public class ex4 {

public static void main(String[] args) {

try{
FileWriter writer1 = new FileWriter("Matrice1.txt");

FileWriter writer2 = new FileWriter("Matrice2.txt");

int s;

for(int i=0;i<5;i++) {

int som=0;

for(int j=0;j<5;j++) {

s=(int)(Math.random()*10+20);

som+=s;

writer1.write(s + " ");}

writer1.write("\n");

writer2.write("ligne "+i+": "+som);

writer2.write("\n");}

writer1.close();

writer2.close();}

catch(FileNotFoundException e){

e.printStackTrace();

catch(IOException e){

e.printStackTrace();

}}
//ex5.6

import java.awt.event.* ;

import javax.swing.* ;

public class ex6 extends JFrame implements ActionListener{

public ex6 (){

setTitle ("Exemple de menus") ;

setSize (300, 130) ;

/* creation barre des menus */

barreMenus = new JMenuBar() ;

setJMenuBar(barreMenus) ;

/* creation menu Fichier et ses options */

fichier = new JMenu ("Fichier") ;

barreMenus.add(fichier) ;

ouvrir = new JMenuItem ("Ouvrir") ;

fichier.add (ouvrir) ;

ouvrir.addActionListener (this) ;

sauvegarder = new JMenuItem ("Sauvegarder") ;

fichier.add (sauvegarder) ;
sauvegarder.addActionListener (this) ;

fermer = new JMenuItem ("Fermer") ;

fichier.add (fermer) ;

fermer.addActionListener (this) ;

/* creation menu Edition et ses options*/

edition = new JMenu ("Edition") ;

barreMenus.add (edition) ;

copier = new JMenuItem ("Copier") ;

edition.add (copier) ;

copier.addActionListener (this) ;

coller = new JMenuItem ("Coller") ;

edition.add (coller) ;

coller.addActionListener (this) ;

/* etat initial : pas de fichier ouvert, pas d'info copiee */

fichierOuvert = false ; infoCopiee = false ;

nomFichier = null ;

public void actionPerformed (ActionEvent e){

Object source = e.getSource() ;

if (source == ouvrir){

String nom = JOptionPane.showInputDialog (this, "nom fichier a ouvrir") ;

if ((nom == null) || (nom.equals(""))) return ;

if (fichierOuvert) System.out.println ("On ferme " + nomFichier) ;

nomFichier = nom ; fichierOuvert = true ;

System.out.println ("On ouvre " + nomFichier) ;}

if (source == fermer){

if (fichierOuvert) System.out.println ("On ferme " + nomFichier) ;

else System.out.println ("pas de fichier ouvert") ;


fichierOuvert = false ;}

if (source == sauvegarder){

if (fichierOuvert) System.out.println ("on sauvegarde " + nomFichier) ;

else System.out.println ("Pas de fichier ouvert a sauvegarder") ;}

if (source == copier){

System.out.println ("copie d'information") ;

infoCopiee = true ;}

if (source == coller){

if (infoCopiee) System.out.println ("collage d'information") ;

else System.out.println ("Rien a coller") ;

infoCopiee = false ;}

private JMenuBar barreMenus ;

private JMenu fichier, edition ;

private JMenuItem ouvrir, sauvegarder, fermer, copier, coller ;

private boolean fichierOuvert, infoCopiee ;

private String nomFichier ;

public static void main (String args[]){

ex6 fen = new ex6() ;

fen.setVisible(true) ;}

‫ وربي يوقفنا أجمعين‬، ‫ادعولي معاكم فضال‬

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy