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

EDT/SwingWorker Java Discussion :

Recherche une âme charitable pour expliciter l'EDT


Sujet :

EDT/SwingWorker Java

  1. #1
    Membre régulier Avatar de Sylvain__A_
    Homme Profil pro
    Développeur Java
    Inscrit en
    Octobre 2008
    Messages
    100
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : Communication - Médias

    Informations forums :
    Inscription : Octobre 2008
    Messages : 100
    Points : 94
    Points
    94
    Par défaut Recherche une âme charitable pour expliciter l'EDT
    J'ai vraiment beaucoup de mal à comprendre le concept d'EDT.

    Je n'arrive pas à placer correctement un écouteur qui customise l'action de fermer la fenêtre principale et quitter le programme. Quoique je fasse, j'ai cette exception :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    Exception in thread "AWT-EventQueue-0" java.lang.Error: Cannot call invokeAndWait from the event dispatcher thread
    Je pensais que justement, appeler SwingUtilities.invokeAndWait ou SwingUtilities.invokeLater permettait d'obtenir des applications thread safe ...

    Voici mon architecture :

    DeviceManager est mon programme principal, c'est une classe statique, dans laquelle au sein du main, j'instancie ma classe WindowManager, et essaie de placer un écouteur sur l'évenement Closing, afin de pouvoir fermer facilement d'autres thread, dont j'ai les références ici, et que je n'aurais pas dans la classe windowManager.

    Voici mon main :

    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
     
    public static void main( String[] args )
    {
    	_window  = new WindowManager( "Les Tanukis : Java serial - socket daemon." );
     
    	WindowListener wListener = new WindowAdapter()
    	{
    		public void windowClosing( WindowEvent e )
    		{
    			int confirm = JOptionPane.showOptionDialog( _window.get_mainFrame(), "Really Exit?", "Exit Confirmation",
    					JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null );
    			if ( confirm == 0 )
    			{
    				try {
    					SwingUtilities.invokeAndWait(
    						new Runnable(){
    							public void run(){
    								_window.get_mainFrame().dispose();
    							}
    						}
    					);
    				} catch ( InterruptedException ee) {
    					ee.printStackTrace();
    				} catch ( InvocationTargetException eee) {
    					eee.printStackTrace();
    				}
     
    				if( DeviceManager.getSocket() != null )
    					DeviceManager.getSocket().closeConnection();
    				if( DeviceManager.getSerialListener() != null )
    					DeviceManager.getSerialListener().close();
    				if( DeviceManager.getPrinter() != null ){
    					PrinterManager pm = DeviceManager.getPrinter();
    					pm = null;
    				}
    				System.exit(0);
    			}
    		}
    	};
    	_window.get_mainFrame().addWindowListener( wListener );
     
    	_printer = new PrinterManager( _window );
     
            ...
    Ce code lance une exception après avoir ouvert le JOptionPAne :

    Exception in thread "AWT-EventQueue-0" java.lang.Error: Cannot call invokeAndWait from the event dispatcher thread

    Voici le code de WindowManager, le constructeur :

    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
     
    public WindowManager( String title ) throws HeadlessException
    {
    	try {
    		javax.swing.SwingUtilities.invokeAndWait( 
    			new Runnable() {
    				public void run() {
    			    	JFrame.setDefaultLookAndFeelDecorated(true);
    					JDialog.setDefaultLookAndFeelDecorated(true);
     
    					try {
    						UIManager.setLookAndFeel(new SubstanceBusinessLookAndFeel() );
    					}
    					catch (UnsupportedLookAndFeelException e1){
    						e1.printStackTrace();
    					}
     
    					_mainFrame.setDefaultCloseOperation( WindowConstants.DO_NOTHING_ON_CLOSE );
    					_mainFrame.setSize(400, 300);
     
    					try {
    						set_icon( ImageIO.read( getClass().getResource("assets/1265388043_socket.png")));
    					}
    					catch ( IOException e ) {
    						e.printStackTrace();
    					}
     
    					_mainFrame.setIconImage(get_icon());
    					_mainFrame.setVisible(true);
     
    					set_mainLayout( new GridBagLayout() );
     
    					_mainFrame.setLayout( get_mainLayout() );
     
    					set_mainTxtarea(new JTextArea());
     
    					addComponent( _mainFrame, get_mainTxtarea(), 0, 0, 2, 3, GridBagConstraints.CENTER, GridBagConstraints.BOTH );
     
    				}
    			}
    		);
    	} catch (InterruptedException e1) {
    		e1.printStackTrace();
    	} catch (InvocationTargetException e1) {
    		e1.printStackTrace();
    	}
     
    }
    Quelqu'un pourrait il m'expliquer ce que je n'arrive pas à comprendre, c'est à dire à quoi sert exactement invokeAndWait, et pourquoi ce code n'est pas thread safe ...

  2. #2
    Expert confirmé
    Profil pro
    Inscrit en
    Août 2006
    Messages
    3 274
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Août 2006
    Messages : 3 274
    Points : 4 141
    Points
    4 141
    Par défaut
    Les listeners sont gérés par l'EDT, donc tu n'as pas besoin de faire ton invokeAndWait pour exécuter ton code.

  3. #3
    Membre régulier Avatar de Sylvain__A_
    Homme Profil pro
    Développeur Java
    Inscrit en
    Octobre 2008
    Messages
    100
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : Communication - Médias

    Informations forums :
    Inscription : Octobre 2008
    Messages : 100
    Points : 94
    Points
    94
    Par défaut
    Merci de ta réponse

    Ce n'est pas "mon" invokeAndWait, je le voit dans beaucoup de doc, il semble que ça soit une bonne pratique ...

    Par ex, je site "The Definitive Guide To Java Swing", 3ed, John Zukowski, p46 :

    To demonstrate the proper way to create a Swing-based program, Listing 2-1 shows the source for a selectable button :
    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
     
    public class ButtonSample {
        public static void main(String args[]) {
            Runnable runner = new Runnable() {
                public void run() {
                    JFrame frame = new JFrame("Button Sample");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    JButton button = new JButton("Select Me");
     
                    // Define ActionListener
                    ActionListener actionListener = new ActionListener() {
                        public void actionPerformed(ActionEvent actionEvent) {
                            System.out.println("I was selected.");
                    }
                };
     
                // Attach listeners
                button.addActionListener(actionListener);
     
                frame.add(button, BorderLayout.SOUTH);
                frame.setSize(300, 100);
                frame.setVisible(true);
            }
        };
        EventQueue.invokeLater(runner);
        }
    }
    Ma question portait sur le comment organiser, écouter, correctement l'évenement windowClosing, sachant que ma fenetre est crée dans le constructeur de la classe WIndowManager, et que je voudrais, si c'est possible, écouter dans mon "Main", afin de disposer facilement de références vers d'autres thread de mon programme.

  4. #4
    Expert confirmé
    Profil pro
    Inscrit en
    Août 2006
    Messages
    3 274
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Août 2006
    Messages : 3 274
    Points : 4 141
    Points
    4 141
    Par défaut
    La différence entre ce bloc de code et le tien, c'est que là, au début de ton main, on est pas encore dans l'EDT, donc on fait appel à invokeLater pour l'initialisation des composants.

    Effectivement, invokeLater ou son cousin invokeAndWait font partie des bonnes pratiques, quand on sait s'en servir.

    Pour en revenir à ton problème, tu vires donc l'appel à l'une de ces méthodes qui ne sert à rien.
    Pour le reste, je n'ai toujours pas bien compris ce que tu cherches à faire.
    Qu'est-ce qui t'empêche d'avoir des références vers d'autres threads ?

  5. #5
    Rédacteur/Modérateur

    Avatar de bouye
    Homme Profil pro
    Information Technologies Specialist (Scientific Computing)
    Inscrit en
    Août 2005
    Messages
    6 854
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 48
    Localisation : Nouvelle-Calédonie

    Informations professionnelles :
    Activité : Information Technologies Specialist (Scientific Computing)
    Secteur : Agroalimentaire - Agriculture

    Informations forums :
    Inscription : Août 2005
    Messages : 6 854
    Points : 22 878
    Points
    22 878
    Billets dans le blog
    51
    Par défaut
    Quand on est dans l'EDT, invokeLater() oui , invokeAndWait() non !

    Quand on est hors de l'EDT, invokeLater() oui , invokeAndWait() attention ca peut quand meme mener a des locks !

    SwingUtilities contient une methode qui permet de tester si on est bien dans l'EDT et sinon c'est assez facile de tester la valeur retournee par Thread.currentThread(). Ca permet de faire des propagation d'evenement du style :

    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
     
    public void setTruc(final Object value) {
      // Do stuff.
      if (SwingUtilities.isEventDispatchTread()) {
        [...]
      }
      // Start again at EDT.
      else {
         SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
              setTruc(value)
            }
         });
      }
    }

  6. #6
    Expert confirmé
    Profil pro
    Inscrit en
    Août 2006
    Messages
    3 274
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Août 2006
    Messages : 3 274
    Points : 4 141
    Points
    4 141
    Par défaut
    Quand on est dans l'EDT, invokeLater() oui
    Quel est l'intérêt d'appeler invokeLater si on est déjà dans l'EDT ?

  7. #7
    Expert éminent sénior
    Avatar de sinok
    Profil pro
    Inscrit en
    Août 2004
    Messages
    8 765
    Détails du profil
    Informations personnelles :
    Âge : 44
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Août 2004
    Messages : 8 765
    Points : 12 977
    Points
    12 977
    Par défaut
    Citation Envoyé par fr1man Voir le message
    Quel est l'intérêt d'appeler invokeLater si on est déjà dans l'EDT ?
    Aucune mais ça marche sans bug .

  8. #8
    Expert confirmé
    Profil pro
    Inscrit en
    Août 2006
    Messages
    3 274
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Août 2006
    Messages : 3 274
    Points : 4 141
    Points
    4 141
    Par défaut
    Aucune mais ça marche sans bug .

    On est d'accord, mais bon, complexifier le code alors que ça ne sert à rien (dans ce cas précis), je trouve cela dommage.

  9. #9
    Membre régulier Avatar de Sylvain__A_
    Homme Profil pro
    Développeur Java
    Inscrit en
    Octobre 2008
    Messages
    100
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : Communication - Médias

    Informations forums :
    Inscription : Octobre 2008
    Messages : 100
    Points : 94
    Points
    94
    Par défaut
    Merci de prendre le temps de poster.

    Je site un long passage de "Filthy Rich Clients", Addison-Wesley, de Chet Haase et Romain Guy, 2007, Chap 2, p 60 :

    Threading
    As we discussed earlier, Swing relies on the older AWT GUI toolkit for top-level window support and event dispatching. Whenever you run a Swing application, three threads are automatically created. The first one is the main thread, which runs your application’s main method. A second thread, called the toolkit thread, is in charge of capturing the system events, like keyboard key presses or mouse movements. Although this thread is vital, it is only part of AWT implementation and never runs application code. Capture events are sent over to a third thread, the EDT. The EDT is very important because it is in charge of dispatching the events captured by the toolkit thread to the appropriate components and calling the painting methods. It is also the thread on which you interact with Swing. For instance, if you press a key in a JTextField, the EDT dispatches the key press events to the component’s key listener. The component then updates its model and posts a paint request to the event queue. The EDT dequeues the paint request and notifies the component a second time, asking it to repaint itself. In short, everything in AWT and Swing happens on the EDT. Note that if events are received faster
    than they can be delivered, the EDT queues them until they can be processed. While easy to understand on the surface, this simple threading model can yield poor performance in Swing applications if the implications of the Swing’s singlethreaded model are not considered. Indeed, performing a long operation on the EDT, such as reading or writing a file, will block the whole UI. No event can then be dispatched and no update of the screen can be performed while the long operation is underway. The result from the user perspective is that the application appears to be hung or, at least, very slow.
    Poorly written applications that block the EDT for long periods of time have
    contributed to some people thinking that Swing itself is slow. Most Swing
    application performance issues are actually perceived performance issues. The
    Swing components dispatch their work quite quickly. However, when the application blocks the EDT, it freezes the user interface and the user thinks the application runs slowly. Freezing happens, for instance, when you have long computations or I/O accesses running in a method executed by the EDT.
    The following example, available on the book’s Web site, exhibits such behavior. Run the application and click the Freeze button. It should remain pressed for a few seconds. Whenever the user clicks on a button, the actionPerformed() method of the button’s ActionListener is called. Since this action is triggered by an event, actionPerformed() is invoked on the EDT. In this particular case, the code pauses the current thread for 4 seconds, emulating a long operation that blocks Swing’s ability to dispatch events and repaint the GUI. The following example shows that failure to understand and master Swing’s threading can lead to applications that perform poorly.
    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
     
    public class FreezeEDT extends JFrame implements ActionListener {
        public FreezeEDT() {
            super("Freeze");
            JButton freezer = new JButton("Freeze");
            freezer.addActionListener(this);
            add(freezer);
            pack();
        }
     
        public void actionPerformed(ActionEvent e) {
        // Simulates a long running operation.
        // For instance: reading a large file,
        // performing network operations, etc.
            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {}
        }
     
        public static void main(String... args) {
            FreezeEDT edt = new FreezeEDT();
            edt.setVisible(true);
        }
    }
    Threading Model

    Swing’s threading model is based on a single rule: The EDT is responsible for
    executing any method that modifies a component’s state. This includes any component’s constructor. According to this rule, and despite what you can read in many books and tutorials about Swing, the main() method in the previous code example is invalid and can cause a deadlock. Because the JFrame is a Swing component, and because it instantiates another Swing component, it should be created on the EDT, not on the main thread.
    Swing is not a “thread-safe” API. It should be invoked only on the EDT. The
    great minds behind Swing made this choice on purpose to guarantee the order
    and predictability of events. A single-threaded API is also much simpler to
    understand and debug than a multithreaded one. Incidentally, Swing is not the only single-threaded graphical toolkit: SWT, QT, and .NET WinForms provide a similar threading model. Now that you know that you must avoid performing any lengthy operations on the EDT, you need to find a solution to this common problem. The first answer that springs to mind is to use another thread, as in the following code example. In this actionPerformed() method, a new thread is spawned to read a large file (of, say, several megabytes) and add the results in a JTextArea:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
     
    public void actionPerformed( ActionEvent e ) {
        new Thread(new Runnable() {
            public void run() {
                String text = readHugeFile();
                // Bad code alert: modifying textArea on this thread
                // violates the EDT rule
                textArea.setText(text);
            }
        }).start();
    }
    At first, this code seems to be the solution to your problem, as it does not block the EDT. Unfortunately, it violates Swing’s single-thread rule: it doesn’t modify the text component’s state on the EDT. Doing so will not necessarily cause any trouble during your tests, but a deadlock can appear anytime, and more often than not, it will happen when one of your customers is using the application. Tracking down and fixing such a bug is very difficult and time consuming, so it is highly recommended to always follow Swing’s single-threading rule.

    Invoke Later

    But don’t fret! Swing offers three very useful methods to deal with the EDT in
    the class javax.swing.SwingUtilities. The first of these methods is called
    invokeLater(), and it can be used to post a new task on the EDT. Here is how
    you can rewrite the previous example to be both nonblocking and correct:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
     
    public void actionPerformed( ActionEvent e ) {
        new Thread(new Runnable() {
            public void run() {
                final String text = readHugeFile();
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        textArea.setText(text);
                    }
                });
            }
        }).start();
    }
    In the new version of the code, the application posts a Runnable task that updates the content of the text area on the EDT. The invokeLater() implementation takes care of creating and queuing a special event that contains the Runnable. This event is processed on the EDT in the order it was received, just like any other event. When its time comes, it is dispatched by running the Runnable’s run() method. Using invokeLater() is as simple as passing a Runnable instance whose sole method, run(), contains the code you wish to execute on the EDT. So what exactly happens in this code? First, the user clicks on a button and the EDT invokes actionPerformed(). Then, the application creates and starts a new thread, which reads the content of a file and stores it in a String. Finally, a new task, the Runnable instance, is created and placed in the queue of the EDT thanks to invokeLater(). Now that you know how to force a block of code to be invoked on the EDT, it is easy to fix the main() method of the first example:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
     
    public static void main( String... args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                FreezeEDT edt = new FreezeEDT();
                edt.setVisible(true);
            }
        });
    }
    Is This the EDT?

    The second SwingUtilities method that makes it easier to work with Swing’s
    threading model is called isEventDispatchThread(). When invoked, this
    method returns true if the calling code is currently being executed on the EDT, false otherwise. You can therefore create methods that can be called from the EDT and any other thread and still obey the rule, as shown in the following example.

    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
     
    private void incrementLabel() {
        tickCounter++;
        Runnable code = new Runnable() {
            public void run() {
                counter.setText(String.valueOf(tickCounter));
            }
        };
        if (SwingUtilities.isEventDispatchThread()) {
            code.run();
        }
        else {
            SwingUtilities.invokeLater(code);
        }
    }
    This method uses an integer, tickCounter, to change the text of a JLabel called counter. When incrementLabel() is called from the EDT, the code executes directly. Otherwise, invokeLater() is used to schedule the task for the EDT. A full working version of this example can be found on the book’s Web site under the name SwingThreading. The third and last SwingUtilities method related to threading, invokeAndWait(), is also the least commonly used (which is probably a good thing, as we will see). Its behavior is similar to invokeLater() in that it allows you to post a Runnable task to be executed on the EDT. The difference is that invokeAndWait() blocks the current thread and waits until the EDT is done executing the task. Let us imagine an intelligent application that can detect when the time it has spent reading a file has exceeded some threshold. This application reads a file in a separate thread and, after 10 seconds of work, asks the user whether he would
    like to continue or cancel the operation. To implement such a feature, you would normally initialize a lock to stop the reader thread and then display a dialog box on the EDT. Writing such a piece of code is possible but dangerous because you can easily introduce a deadlock. The following example shows how you can use invokeAndWait() to do the job safely. The complete, executable version of this example is called SwingThreadingWait and can be found on the book’s Web site.

    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
     
    try {
        // Holds the answer to the dialog box
        final int[] answer = new int[1];
        // Pauses the current thread until the dialog box
        // is dismissed
        SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
                answer[0] = JOptionPane.showConfirmDialog(null,"Abort long operation?", "Abort?", JOptionPane.YES_NO_OPTION);
            }
        });
        if (answer[0] == JOptionPane.YES_OPTION) {
            return;
        }
        } catch (InterruptedException ie) {
        } catch (InvocationTargetException ite) {
    }
    Swing developers should be aware, however, that there is deadlock potential in invokeAndWait(), as there is in any code that creates a thread interdependency. If the calling code holds some lock (explicitly or implicitly) that the code called through invokeAndWait() requires, then the EDT code will wait for the non-EDT code to release the lock, which cannot happen because the non-EDT code is waiting for the EDT code to complete, and the application will hang. In general, invokeAndWait() may appear simpler to use than invokeLater(), because it executes a Runnable task synchronously, and it would seem as though you don’t have to worry about more than one thread executing your code at the same time. But it is risky to use if you are not absolutely sure of the threading and locking dependencies that you are creating, so it should be used only in very clearly risk-free situations.
    Besides the three utility methods just covered, every Swing component offers two useful methods that can be called from any thread: repaint() and revalidate(). The latter forces a component to lay out its children, and the former simply refreshes the display. These two methods do their work on the EDT, no matter what thread you invoke them on. The repaint() method is widely used throughout the Swing API to synchronize components’ properties and the screen. For instance, when you change the foreground color of a button by calling JButton.setForeground(Color), Swing stores the new color and calls repaint() to automatically show the new value of the color property. Calling repaint() triggers the execution of several other methods on the EDT, including paint() and paintComponent(). If you place the following component in a JFrame and spawn a new thread called repaint() on the component, you will always see the message “true” in the console output. The complete running example, called SafeRepaint, can be found on this book’s Web site.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
    public class SafeComponent extends JLabel {
        public SafeComponent() {
            super("Safe Repaint");
        }
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            System.out.println(SwingUtilities.isEventDispatchThread());
        }
    }

  10. #10
    Expert confirmé
    Profil pro
    Inscrit en
    Août 2006
    Messages
    3 274
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Août 2006
    Messages : 3 274
    Points : 4 141
    Points
    4 141
    Par défaut
    Et donc, quelle est ta question ?

  11. #11
    Expert éminent sénior
    Avatar de sinok
    Profil pro
    Inscrit en
    Août 2004
    Messages
    8 765
    Détails du profil
    Informations personnelles :
    Âge : 44
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Août 2004
    Messages : 8 765
    Points : 12 977
    Points
    12 977
    Par défaut
    Sinon tu pouvais juste lier le tuto de Romain Guy (aka gfx en ces lieux) sur le sujet.

    http://gfx.developpez.com/tutoriel/j...ing-threading/

  12. #12
    Membre régulier Avatar de Sylvain__A_
    Homme Profil pro
    Développeur Java
    Inscrit en
    Octobre 2008
    Messages
    100
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : Communication - Médias

    Informations forums :
    Inscription : Octobre 2008
    Messages : 100
    Points : 94
    Points
    94
    Par défaut


    Rien, rien, j'apporte ma pierre au débat.

    J'ai re-factoré mon code, dans mon Main, j'ai crée des getters vers les variables que je voulais fermer à la fermeture de la fenêtre (le serveur de Socket, l'écouteur de port série), et dans WindowManager j'ai viré tous les appels à InvokeAndWait (dont j'avais mal compris le role), remplacé par invokeLater, et écoute l'évenement WindowCLosing au sein de celui-ci, utilisant les getters pour fermer ce que je voulais.

    Je taggue résolu, merci à vous.

  13. #13
    Membre régulier Avatar de Sylvain__A_
    Homme Profil pro
    Développeur Java
    Inscrit en
    Octobre 2008
    Messages
    100
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : Communication - Médias

    Informations forums :
    Inscription : Octobre 2008
    Messages : 100
    Points : 94
    Points
    94
    Par défaut
    Oui effectivement, le tuto est très bien, je ne l'avais pas vu, le coté Java de developpez est tellement riche que c pas étonnant

  14. #14
    Rédacteur/Modérateur

    Avatar de bouye
    Homme Profil pro
    Information Technologies Specialist (Scientific Computing)
    Inscrit en
    Août 2005
    Messages
    6 854
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 48
    Localisation : Nouvelle-Calédonie

    Informations professionnelles :
    Activité : Information Technologies Specialist (Scientific Computing)
    Secteur : Agroalimentaire - Agriculture

    Informations forums :
    Inscription : Août 2005
    Messages : 6 854
    Points : 22 878
    Points
    22 878
    Billets dans le blog
    51
    Par défaut
    Citation Envoyé par fr1man
    Quel est l'intérêt d'appeler invokeLater si on est déjà dans l'EDT ?
    Citation Envoyé par Sinok
    Aucune mais ça marche sans bug .
    Citation Envoyé par fr1man
    On est d'accord, mais bon, complexifier le code alors que ça ne sert à rien (dans ce cas précis), je trouve cela dommage.
    Bien au contraire, ca a l'utilite de pouvoir deporter le traitement EDT (puisque c'est ce dont il s'agit ici) a un moment ou on aura plus de temps pour l'effectuer. Il n'est pas forcement utile de repondre tout instantenement/de suite/maintenant a tous les clics de boutons. Ex : deporter la construction/instanciation d'une boite de dialogue lourde plus tard, tout en permettant de ne pas bloquer la fin de l'animation du bouton.
    Meme chose pour des propagations d'evenements ou de proprietes assez lourdes.

  15. #15
    Expert confirmé
    Profil pro
    Inscrit en
    Août 2006
    Messages
    3 274
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Août 2006
    Messages : 3 274
    Points : 4 141
    Points
    4 141
    Par défaut
    @ bouye
    Je comprends ce que tu veux dire, mais dans ce cas précis, on veut juste fermer la fenêtre. On ne veut pas remettre le traitement à plus tard.
    Dans d'autres cas, je veux bien.

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

Discussions similaires

  1. Réponses: 0
    Dernier message: 06/10/2009, 10h26
  2. Recherche une distribution linux pour netbook
    Par ThitoO dans le forum Distributions
    Réponses: 2
    Dernier message: 12/02/2009, 17h13
  3. Réponses: 0
    Dernier message: 13/11/2008, 23h07
  4. [DOS] Je recherche une commande dos pour graver
    Par tomblaireau dans le forum Scripts/Batch
    Réponses: 4
    Dernier message: 01/04/2007, 09h25
  5. recherche une classe KZtransImg pour delphi 7
    Par plante20100 dans le forum Composants VCL
    Réponses: 2
    Dernier message: 21/07/2005, 13h56

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