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

Composants Java Discussion :

[JProgressBar] Comment l'utiliser


Sujet :

Composants Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre averti
    Profil pro
    Inscrit en
    Novembre 2003
    Messages
    30
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2003
    Messages : 30
    Par défaut [JProgressBar] Comment l'utiliser
    dans une interface graphique,
    j'ai une série d'actions qui peut prendre plusieurs secondes,
    je voudrais donc ajouter une JProgressBar...

    cette série d'actions se déclenche lorsque je clique sur
    "yes" dans une boite de dialogue, les actions sont des
    appels de methodes d'une autre classe, donc je ne peux
    pas faire des incrémentations de la JProgressBar
    au fur et à mesure du déroulement des actions..

    est-il possible de faire en sorte que la JProgressBar
    démarre dans un thread en // au début d'un bloc d'instructions
    et qu'elle s'arrete à la fin de ce bloc?

    par exemple :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    if(retour == JOptionPane.YES_OPTION){
    // Demarrage de JProgressBar
    ballala appel de methodes d'une autre classe
    // Arrete de JProgressBar				
    }

  2. #2
    Membre confirmé Avatar de spoutyoyo
    Inscrit en
    Avril 2004
    Messages
    116
    Détails du profil
    Informations forums :
    Inscription : Avril 2004
    Messages : 116
    Par défaut
    Je viens de la faire dans mon application. Ce n'est peut être pas la méthode la plus propre, mais c'est celle que j'ai compris en lisant des posts sur ce forum et la FAQ.
    Je te post un exemple
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    Wait wait = new Wait(parent, Textes.VIEW);
     
    Runnable runnable = new ThreadViewForm();
    Thread thread = new Thread(runnable);
    thread.start();
    où Wait est la JDialog avec la JProgressBar et ThreadViewForm, le thread qui execute le traitement.

    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
     
    public class ThreadViewForm implements Runnable{
     
     
     
        public ThreadViewForm(){
     
        }
     
     
        public void run() {
     
            wait.show();
            // Traitement à exécuter
            wait.dispose();
          }
     
        }    
     
    }

  3. #3
    Membre éprouvé Avatar de Actarus78
    Homme Profil pro
    Ingénieur qualité méthodes
    Inscrit en
    Septembre 2005
    Messages
    87
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 46
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur qualité méthodes
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Septembre 2005
    Messages : 87
    Par défaut
    Tu peux aussi trouver un joli tuto dans les faq java sur ce site.

    Sinon pour ma part j'utilise un SwingWorker

    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
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    import javax.swing.SwingUtilities;
     
    /**
     * This is the 3rd version of SwingWorker (also known as
     * SwingWorker 3), an abstract class that you subclass to
     * perform GUI-related work in a dedicated thread.  For
     * instructions on and examples of using this class, see:
     * 
     * http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html
     *
     * Note that the API changed slightly in the 3rd version:
     * You must now invoke start() on the SwingWorker after
     * creating it.
     */
    public abstract class SwingWorker {
        private Object value;  // see getValue(), setValue()
     
        /** 
         * Class to maintain reference to current worker thread
         * under separate synchronization control.
         */
        private static class ThreadVar {
            private Thread thread;
            ThreadVar(Thread t) { thread = t; }
            synchronized Thread get() { return thread; }
            synchronized void clear() { thread = null; }
        }
     
        private ThreadVar threadVar;
     
        /** 
         * Get the value produced by the worker thread, or null if it 
         * hasn't been constructed yet.
         */
        protected synchronized Object getValue() { 
            return value; 
        }
     
        /** 
         * Set the value produced by worker thread 
         */
        private synchronized void setValue(Object x) { 
            value = x; 
        }
     
        /** 
         * Compute the value to be returned by the <code>get</code> method. 
         */
        public abstract Object construct();
     
        /**
         * Called on the event dispatching thread (not on the worker thread)
         * after the <code>construct</code> method has returned.
         */
        public void finished() {}   	
     
        /**
         * A new method that interrupts the worker thread.  Call this method
         * to force the worker to stop what it's doing.
         */
        public void interrupt() {
            Thread t = threadVar.get();
            if (t != null) {
                t.interrupt();
            }
            threadVar.clear();
        }
     
        /**
         * Return the value created by the <code>construct</code> method.  
         * Returns null if either the constructing thread or the current
         * thread was interrupted before a value was produced.
         * 
         * @return the value created by the <code>construct</code> method
         */
        public Object get() {
            while (true) {  
                Thread t = threadVar.get();
                if (t == null) {
                    return getValue();
                }
                try {
                    t.join();
                }
                catch (InterruptedException e) {
                    Thread.currentThread().interrupt(); // propagate
                    return null;
                }
            }
        }
     
     
        /**
         * Start a thread that will call the <code>construct</code> method
         * and then exit.
         */
        public SwingWorker() {
            final Runnable doFinished = new Runnable() {
               public void run() { finished(); }
            };
     
            Runnable doConstruct = new Runnable() { 
                public void run() {
                    try {
                        setValue(construct());
                    }
                    finally {
                        threadVar.clear();
                    }
                    SwingUtilities.invokeLater(doFinished);
                }
            };
     
            Thread t = new Thread(doConstruct);
            threadVar = new ThreadVar(t);
        }
     
        /**
         * Start the worker thread.
         */
        public void start() {
            Thread t = threadVar.get();
            if (t != null) {
                t.start();
            }
        }
    }
    *********************************

    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
    /**
         * The actionPerformed method in this class
         * is called each time the Timer "goes off".
         */
        class TimerListener implements ActionListener {
            private LoadChooser loader;
     
        	public TimerListener(LoadChooser lc){
            	this.loader = lc;
            }
     
        	public void actionPerformed(ActionEvent evt) {
                try{
    	    		progressMonitor.setProgress(taskxml.getCurrent());
    	            String s = taskxml.getMessage();
    	            progressMonitor.setNote(s);
    	            if (s != null) {
    	                progressMonitor.setNote(s);
    	            }
    	            if(progressMonitor.isCanceled()){
    	            	Log.setInfo("User has canceled the preload.");
    	            	System.exit(0);
    	            }
    	            if (progressMonitor.isCanceled() || taskxml.isDone()) {
    	                progressMonitor.close();
    	                taskxml.stop();
    	                timer.stop();
    	                try{
    		                Object[] o = {this.loader};
    		                next[0].newInstance(o);
    		                o = null;
    	                }catch(Exception e){
    	                	if(Log.getLevelError()>=6)Log.setExceptionInfo(e);
    	                	if(Log.getLevelError()>=6)Log.setInfo("The next object called should have a constructor with LoadChooser as paramametter");
    		                Object[] o = {};
    		                next[0].newInstance(o);
    		                o = null;
    	                }
     
    	            }
                }catch(Exception e){
                	if(Log.getLevelError()>=6)Log.setExceptionInfo(e);
                }
            }
        }
    *****************************
    Dans ta classe où se trouve ton bouton qui déclenche l'action :

    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
    //Create a timer.
       timer = new Timer(ONE_SECOND, new TimerListener(this));
     
    public void actionPerformed(ActionEvent e) {
    		try{
    			if(e.getSource()==tonBoutton){
     
    				taskxml = new Longtask();//class qui déclenchera tes series d'actions
     
    				progressMonitor = new ProgressMonitor(this,"Loading ","", 0, taskxml.getLengthOfTask());
    				progressMonitor.setProgress(0);
    				progressMonitor.setMillisToPopup(ONE_SECOND/2);
     
    				taskxml.go();
    				timer.start();
    				this.setVisible(false);
    			}
     
    		}catch(Exception ex){
    Log.setExceptionInfo(ex);
    		}
    *********************
    Enfin ta class qui gére tes sries d'actions :

    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
    public class LongTask {
     
        private int current 		= 0;
        private boolean done 		= false;
        private boolean canceled 	= false;
     
        private int lengthOfTask;
        private String statMessage;
     
     
        public LongTask() {
            //Compute length of task...
        }
     
    	/**
             * Called  to start the task.
             */
    	public void go() {
    	    final SwingWorker worker = new SwingWorker() {
    	        public Object construct() {
    	            current = 0;
    	            done = false;
    	            canceled = false;
    	            statMessage = null;
    	            return new ActualTask();
    	        }
    	    };
    	    worker.start();
    	}
     
        /**
         * Called to find out how much work needs
         * to be done.
         */
        public int getLengthOfTask() {
            return lengthOfTask;
        }
     
        /**
         * Called to find out how much has been done.
         */
        public int getCurrent() {
            return current;
        }
     
        public void stop() {
        	canceled 		= true;
            statMessage 	= null;
        }
     
        /**
         * Called to find out if the task has completed.
         */
        public boolean isDone() {
            return done;
        }
     
        /**
         * Returns the most recent status message, or null
         * if there is no current status message.
         */
        public String getMessage() {
            return statMessage;
        }
     
        /**
         * The actual long running task.  This runs in a SwingWorker thread.
         */
        class ActualTask {
     
            ActualTask() {
            	try{
    	       	while (!canceled && !done) {
    //Ta serie d'actions avec tes boites de dialogues
     
    	}
     
                        current += 1; //make some progress
                        if (current >= lengthOfTask) {
                            done = true;
                            current = lengthOfTask;
                        }
                        statMessage = "Completed " + current +
                                      " out of " + lengthOfTask + ".";
     
     
    	        	}
          	       	}
    	        	//***End preload Files***
            	}catch (Exception e) {
            		Log.setExceptionInfo(e);
                }
            }

    *******************************

    Tu as normalement toutes les billes en main pour arriver à tes fins, mais il te faudra certainement remanier les classes que je t'ai donné pour pouvoir compiler (retirer par exemple les appels type "Log. " qui font appel à mon propre framework et d'autres peut être que je n'ai pas vu.)

    Bon courrage

  4. #4
    Membre confirmé Avatar de spoutyoyo
    Inscrit en
    Avril 2004
    Messages
    116
    Détails du profil
    Informations forums :
    Inscription : Avril 2004
    Messages : 116
    Par défaut
    Dans mon code, il faut que tu mettes le wait.show qui se trouve dans la méthode run aprés le Thread.start car si tu mets la JDialog modale, cela bloque le traitement aprés.

Discussions similaires

  1. [JProgressBar] Comment l'utiliser ?
    Par itmak dans le forum Composants
    Réponses: 3
    Dernier message: 28/05/2011, 15h30
  2. [Optimisation] Comment bien utiliser le StringBuffer?
    Par mathieu dans le forum Langage
    Réponses: 4
    Dernier message: 17/05/2004, 14h22
  3. Comment bien utiliser ce forum ?
    Par Alcatîz dans le forum Pascal
    Réponses: 0
    Dernier message: 21/04/2004, 16h37
  4. [scrapbook] comment l'utiliser ?
    Par Didier 69 dans le forum Eclipse Java
    Réponses: 4
    Dernier message: 16/04/2004, 17h28
  5. [INDY] -> IdIdentServer comment l'utiliser ?
    Par MaTHieU_ dans le forum C++Builder
    Réponses: 9
    Dernier message: 06/08/2003, 16h00

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