IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

AWT/Swing Java Discussion :

[Débutant] JButton et Thread


Sujet :

AWT/Swing Java

  1. #1
    Membre du Club
    Inscrit en
    Février 2006
    Messages
    102
    Détails du profil
    Informations forums :
    Inscription : Février 2006
    Messages : 102
    Points : 68
    Points
    68
    Par défaut [Débutant] JButton et Thread
    Bonjour,

    Je vous explique mon problème de débutant. J'ai crée un petit formulaire avec un bouton, lorsque je clique dessus je veux qu'une fonction se lance jusqu'à ce que je reclique dessus. D'après ce que j'ai lu, il faut utiliser un thread.

    Le but étant de mettre une petite IHM à un crawler que j'ai réalisé.

    Voila le code actuel :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
     
    import java.awt.BorderLayout;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
     
    public final class MyCrawler extends JFrame implements ActionListener {
     
    	/**
             * @param args
             */
     
    	private JButton button;
    	private JTextField text;
    	private JLabel label;
    	private JFrame frame;
     
    	private boolean isRunning = false;
     
    	private Thread tache;
     
    	public MyCrawler() {
     
    		this.frame = new JFrame();
    		this.frame.setSize(400,200);
    		this.frame.setTitle("CrawlerWeb");
     
    		this.label = new JLabel("WebCrawler");
    		this.label.setHorizontalAlignment(JLabel.CENTER);
    		this.label.setFont(new Font("Verdana", Font.BOLD, 20));
     
    		this.button = new JButton("Start / Stop");
    		this.button.addActionListener(this);
     
    		this.text = new JTextField();
     
    		this.frame.getContentPane().add(label,BorderLayout.NORTH);
    		this.frame.getContentPane().add(text,BorderLayout.CENTER);
    		this.frame.getContentPane().add(button,BorderLayout.SOUTH);
    		this.frame.setVisible(true);
    	}
     
    	public void actionPerformed(ActionEvent e){
    		// Inverse la valeur de la variable (en route/arret)
    		this.isRunning = !this.isRunning;
     
    		if(this.isRunning){
    			System.out.println("C'est parti !");
    			this.tache = new Thread(){
    				public void run(){
    					startCrawling();
    				}
    			};
    			this.tache.start();
    		}
    		else{
    			this.tache.interrupt();
    			System.out.println("On s'arrête !");
    		}
     
    	}
     
    	public static void main(String[] args) {
    		try{
    			// Init thread courant
    			Thread main = Thread.currentThread();
    			// On donne un nom au thread courant
    			main.setName("myMainThread");
    			// Début de main
    			System.out.println("début du thread " + main.getName());
     
    			new MyCrawler();
    			//startCrawling();
     
    			// fin de main
    			System.out.println("fin du thread " + main.getName());
    		}	
    		catch(Exception e){
    			e.printStackTrace();
    		}
    	}
     
    	public static void startCrawling(){
    		while(true){
    			System.out.println("ok");
    		}
    	}
    }
    Lorsque je reclique sur le bouton, rien ne se passe Pourquoi ?

    D'avance merci de m'aiguiller !

  2. #2
    Membre confirmé Avatar de schniouf
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Décembre 2003
    Messages
    382
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 38
    Localisation : Luxembourg

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Opérateur de télécommunications

    Informations forums :
    Inscription : Décembre 2003
    Messages : 382
    Points : 474
    Points
    474
    Par défaut
    Au premier appel de la méthode, this.isRunning vaut false, donc
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    this.isRunning = !this.isRunning ;
    fait que this.isRunning == true.
    Aux passages suivant, this.isRunning vaut true, donc
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    this.isRunning = !this.isRunning ;
    fait que this.isRunning == false !
    Donc tu dois modifier ta variable this.isRunning quelque part dans le code . A toi de chercher !

  3. #3
    Expert éminent sénior
    Avatar de adiGuba
    Homme Profil pro
    Développeur Java/Web
    Inscrit en
    Avril 2002
    Messages
    13 938
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur Java/Web
    Secteur : Transports

    Informations forums :
    Inscription : Avril 2002
    Messages : 13 938
    Points : 23 190
    Points
    23 190
    Billets dans le blog
    1
    Par défaut
    Salut,


    La méthode interrupt() de la classe Thread n'arrête pas réellement le thread : elle se contente de passer son status à "interrupted".

    C'est au code de ton thread de gérer ce status. Certaine méthode bloquante le gère déjà en retournant une exception, mais sinon tu dois le gérer à la main en vérifiant le status du thread de "temps en temps". De plus je te déconseille de faire une attente active ! Rajoutes un sleep() pour laisser un peu de marge au processeur :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    	public static void startCrawling() {
    		Thread current = Thread.currentThread();
    		try {
    			while(!thread.isInterrupted()){
    				System.out.println("ok");
    				Thread.sleep(50);
    			}
    		} catch (InterruptedException e) {
    			// Fin du thread lorsqu'on est dans le sleep()
    		}
    	}
    a++

  4. #4
    Membre du Club
    Inscrit en
    Février 2006
    Messages
    102
    Détails du profil
    Informations forums :
    Inscription : Février 2006
    Messages : 102
    Points : 68
    Points
    68
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
     
    import java.awt.BorderLayout;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
     
    public final class MyCrawler extends JFrame implements ActionListener {
     
    	/**
             * @param args
             */
     
    	private JButton button;
    	private JTextField text;
    	private JLabel label;
    	private JFrame frame;
     
    	private boolean isRunning = false;
     
    	private Thread tache;
     
    	public MyCrawler() {
     
    		this.frame = new JFrame();
    		this.frame.setSize(400,200);
    		this.frame.setTitle("CrawlerWeb");
     
    		this.label = new JLabel("WebCrawler");
    		this.label.setHorizontalAlignment(JLabel.CENTER);
    		this.label.setFont(new Font("Verdana", Font.BOLD, 20));
     
    		this.button = new JButton("Start / Stop");
    		this.button.addActionListener(this);
     
    		this.text = new JTextField();
     
    		this.frame.getContentPane().add(label,BorderLayout.NORTH);
    		this.frame.getContentPane().add(text,BorderLayout.CENTER);
    		this.frame.getContentPane().add(button,BorderLayout.SOUTH);
    		this.frame.setVisible(true);
    	}
     
    	public void actionPerformed(ActionEvent e){
    		// Inverse la valeur de la variable (en route/arret)
    		this.isRunning = !this.isRunning;
     
    		if(this.isRunning){
    			System.out.println("C'est parti !");
    			this.tache = new Thread(){
    				public void run(){
    					startCrawling();
    				}
    			};
    			this.tache.start();
    		}
    		else{
    			this.tache.interrupt();
    			System.out.println("On s'arrête !");
    		}
     
    	}
     
    	public static void main(String[] args) {
    		try{
    			// Init thread courant
    			Thread main = Thread.currentThread();
    			// On donne un nom au thread courant
    			main.setName("myMainThread");
    			// Début de main
    			System.out.println("début du thread " + main.getName());
     
    			new MyCrawler();
    			//startCrawling();
     
    			// fin de main
    			System.out.println("fin du thread " + main.getName());
    		}	
    		catch(Exception e){
    			e.printStackTrace();
    		}
    	}
     
    	public static void startCrawling(){
    		Thread current = Thread.currentThread();
    		try{
    			while(!current.isInterrupted()){
    				System.out.println("ok");
    				current.sleep(500);
    			}
    		}
    		catch(InterruptedException e){
    			e.printStackTrace();
    		}
    	}
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
    début du thread myMainThread
    fin du thread myMainThread
    C'est parti !
    ok
    On s'arrête !
    java.lang.InterruptedException: sleep interrupted
    	at java.lang.Thread.sleep(Native Method)
    	at MyCrawler.startCrawling(MyCrawler.java:87)
    	at MyCrawler$1.run(MyCrawler.java:50)
    Voilà ce que j'ai maintenant, ça à l'air de fonctionner
    Dernière chose, sous Eclipse il me met un Warning sur le nom de la classe avec ce message suivant :

    The serializable class MyCrawler does not declare a static final serialVersionUID field of type long

    Ca veut dire quoi exactement ?

  5. #5
    Expert éminent sénior
    Avatar de adiGuba
    Homme Profil pro
    Développeur Java/Web
    Inscrit en
    Avril 2002
    Messages
    13 938
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur Java/Web
    Secteur : Transports

    Informations forums :
    Inscription : Avril 2002
    Messages : 13 938
    Points : 23 190
    Points
    23 190
    Billets dans le blog
    1
    Par défaut
    Citation Envoyé par ViRouF
    Dernière chose, sous Eclipse il me met un Warning sur le nom de la classe avec ce message suivant :

    The serializable class MyCrawler does not declare a static final serialVersionUID field of type long

    Ca veut dire quoi exactement ?
    [Java 5.0] serial : "serializable class Main has no definition of serialVersionUID"

    C'est pas bien méchant

    a++

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [C#] question de débutant sur les threads?
    Par Jayceblaster dans le forum C#
    Réponses: 6
    Dernier message: 27/11/2006, 10h52
  2. [Débutant] Pb synchronisation thread
    Par Tymk dans le forum Threads & Processus
    Réponses: 3
    Dernier message: 27/11/2006, 00h59
  3. Réponses: 1
    Dernier message: 09/08/2006, 16h04
  4. (toujours débutant) JButton
    Par gloubi dans le forum AWT/Swing
    Réponses: 14
    Dernier message: 04/08/2006, 15h12
  5. [Débutant]Utilisation des Threads
    Par maniolo dans le forum Débuter avec Java
    Réponses: 19
    Dernier message: 10/07/2006, 11h31

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo