1

I found many answers about my question, but I still don't understand why my application does not throw any exceptions. I created a new java form application in NetBeans 8. My form is created and displayed in main method like this:

public static void main(String args[])
    {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try
        {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
            {
                if ("Nimbus".equals(info.getName()))
                {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        }
        catch (ClassNotFoundException ex)
        {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (InstantiationException ex)
        {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (IllegalAccessException ex)
        {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (javax.swing.UnsupportedLookAndFeelException ex)
        {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                new MainForm().setVisible(true);     
            }
        });
    }

So, this new Runnable creates new MainForm and sets it visible.

Then, in my code I start new threads which updates some jButtons and jTextFields. Code below:

private void updateUI() {
        updateUIThread = new Thread(() ->
        { 
            while (true) {
                try {
                    jtfIP.setEnabled(!Start && !autoRec);
                    jtfPort.setEnabled(!Start && !autoRec);
                    jtfSlaveID.setEnabled(!Start && !autoRec);
                    jtfTimeout.setEnabled(!Start && !autoRec);
                    jtfReqInterval.setEnabled(!Start && !autoRec);
                    jCheckBox1.setEnabled(!Start && !autoRec);
                    jCBReconnect.setEnabled(!Start && !autoRec);

                    if (db != null) {
                        if (!db.getIsOpen()) {
                            jPBD.setBackground(Color.RED);
                            jPBD.setForeground(Color.WHITE);
                            jPBD.setText("ER");
                        } else {
                            jPBD.setBackground(Color.GREEN);
                            jPBD.setForeground(Color.BLACK);
                            jPBD.setText("OK ");
                        }
                    } else {
                        jPBD.setBackground(Color.RED);
                        jPBD.setForeground(Color.WHITE);
                        jPBD.setText(" ER ");
                    }


                    if (autoRec){
                        jbtnConnect.setText("Auto");
                        if (Start && Connected) {
                            jbtnConnect.setForeground(Color.BLACK);
                            jbtnConnect.setBackground(Color.GREEN);
                        } else {       
                            jbtnConnect.setForeground(Color.WHITE);
                            jbtnConnect.setBackground(Color.RED);
                        }
                    } else {
                        if (Start) {
                            jbtnConnect.setText("Disconnect");
                            jbtnConnect.setForeground(Color.BLACK);
                            jbtnConnect.setBackground(Color.GREEN);

                        } else {
                            jbtnConnect.setText("Connect");
                            jbtnConnect.setForeground(Color.WHITE);
                            jbtnConnect.setBackground(Color.RED);
                        }
                    }

                    jtfErroriCitire.setText(String.valueOf(totalErrors));

                    try
                    {
                        Thread.sleep(300);
                        jPanel4.repaint(1);
                    }
                    catch (InterruptedException ex)
                    {
                        Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                catch (Exception ex) {
                    Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
        updateUIThread.start();
    }

And there are other threads started like this above and where I get different values which are updated in the above thread.

My question is why my code does not throw any exception regarding UI elements which are updated from another thread? I did NOT use SwingUtilities.invokeLater(new Runnable() { //code here }); And my code executes perfectly...

Thank you!

3
  • Because they don't, it's up to the developer to ensure that they are properly synchronizing the updates with EDT. It is likely that the decision was made not to partly due to the complexity of such a design and partly due to the expense it would be incurred with every method of a component that "might" change the state had to check that was in the correct thread Oct 21, 2014 at 8:56
  • OK, so my code should use SwingUtilities.invokeLater(new Runnable() {}); and my method UpdateUI() should be called within the invokeLater(new Runnable() { updateUI();} or my method should have inside my Thread the invokeLater, like: private void updateUI() { updateUIThread = new Thread(() -> { while (true) { try { SwingUtilities.invokeLater(new Runnable() //code here });
    – serban.b
    Oct 21, 2014 at 9:00
  • When you want to update the UI, you should be doing so from within the context of the EDT. A good way to do this would be to use a SwingWorker and either publish content to be processed in the EDT or trigger property change events... Oct 21, 2014 at 9:30

3 Answers 3

4

Swing is not thread safe and is single threaded. You should never update UI components from outside the Event Dispatching Thread, equally, you should never run long running processes or blocking code within the EDT, as this will prevent it from processing new events within the event queue, causing your app to look like it's hung...because it has...

Take a look at Concurrency in Swing for more details.

After scratching my head for a while, I realised, the simple solution would be to just use javax.swing.Timer

You want to repeat the update at a regular interval (300 milliseconds) and update the UI, perfect, the Swing Timer is capable of scheduling updates at regular intervals and executes it call back within the context of the EDT!

It also has the ability to consolidate repeated calls. This means, if there is already a "timer" action in the event queue, the timer will not generate a new one, preventing from flooding the EDT and cause possible performance issues...

javax.swing.Timer timer = new Timer(300, new ActionListener() {
    public void actionPerformed(ActionEvent evt) {    
        jtfIP.setEnabled(!Start && !autoRec);
        jtfPort.setEnabled(!Start && !autoRec);
        jtfSlaveID.setEnabled(!Start && !autoRec);
        jtfTimeout.setEnabled(!Start && !autoRec);
        jtfReqInterval.setEnabled(!Start && !autoRec);
        jCheckBox1.setEnabled(!Start && !autoRec);
        jCBReconnect.setEnabled(!Start && !autoRec);

        if (db != null) {
            if (!db.getIsOpen()) {
                jPBD.setBackground(Color.RED);
                jPBD.setForeground(Color.WHITE);
                jPBD.setText("ER");
            } else {
                jPBD.setBackground(Color.GREEN);
                jPBD.setForeground(Color.BLACK);
                jPBD.setText("OK ");
            }
        } else {
            jPBD.setBackground(Color.RED);
            jPBD.setForeground(Color.WHITE);
            jPBD.setText(" ER ");
        }


        if (autoRec){
            jbtnConnect.setText("Auto");
            if (Start && Connected) {
                jbtnConnect.setForeground(Color.BLACK);
                jbtnConnect.setBackground(Color.GREEN);
            } else {       
                jbtnConnect.setForeground(Color.WHITE);
                jbtnConnect.setBackground(Color.RED);
            }
        } else {
            if (Start) {
                jbtnConnect.setText("Disconnect");
                jbtnConnect.setForeground(Color.BLACK);
                jbtnConnect.setBackground(Color.GREEN);

            } else {
                jbtnConnect.setText("Connect");
                jbtnConnect.setForeground(Color.WHITE);
                jbtnConnect.setBackground(Color.RED);
            }
        }

        jtfErroriCitire.setText(String.valueOf(totalErrors));
    }
});
timer.start();

See How to use Swing Timers for more details

8
  • thank you for this @MadProgrammer. I read about Swing Timers but didn't use them. My kind of approach I used before in c#, I'm new to java and I'm finding that's a lot different from c#.
    – serban.b
    Oct 21, 2014 at 21:54
  • @serban.b Ain't that the truth :P Oct 21, 2014 at 22:55
  • @MadProgrammer if you're still around: This doesn't work for me. The task is correctly run per the delay, but it still can't update gui elements
    – Blaine
    May 6, 2017 at 13:40
  • @Blaine Works fine for me May 6, 2017 at 21:28
  • @MadProgrammer Hmm... works for me in a simplified code too. Something's odd with my other 700 lines. Weird...
    – Blaine
    May 7, 2017 at 2:08
1

Swing says you shouldn't update components from outside the Swing Event Dispatch Thread, but it doesn't enforce that. It's just not at all practical to check to see which Thread every single call is coming from.

Also, because of the nature of the problems that tend to result from threading issues (just generally), you should not expect Exceptions to always be thrown when you have a bug in multi-threaded code. This is because threading issues frequently result in deadlock or memory consistency errors, which are in most cases not recoverable (usually the whole JVM just crashes).

3
  • Thanks, it's clear now. I read about SwingWorker (what @MadProgrammer said) and I find out that this is the correct implementation, but I found that it's OK to do it with SwingUtilities.invokeLater(new Runnable() public void run() {//updateUI(); } }); which I think is a lot easier than SwingWorker, but I don't really know if it's 100% safe or correct to use it.
    – serban.b
    Oct 21, 2014 at 19:24
  • Yes, it's always safe to use SwingUtilities.invokeLater(Runnable). SwingWorkers are a little different, though. invokeLater allows you to run your code on the Swing EDT, while a SwingWroker provides a way for you to run code on a separate background thread, and then update the UI from the swingWroker's done method whenever the background thread is finished. Oct 21, 2014 at 19:47
  • @serban.b SwingWorker becomes more useful when you need to change multiple states of different components, as it provides simple to use methods to not only synchronise the updates back to the EDT (via things like publish/process) but also to pass information between the worker and the EDT, via the PropertyChangeListener support...try passing variables around with SwingUtilities... Oct 21, 2014 at 21:02
1

And I did this.

private void updateUI() {
    updateUIThread = new Thread(() ->
    { 
        while (true) {
            try {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        jtfIP.setEnabled(!Start && !autoRec);
                        jtfPort.setEnabled(!Start && !autoRec);
                        jtfSlaveID.setEnabled(!Start && !autoRec);
                        jtfTimeout.setEnabled(!Start && !autoRec);
                        jtfReqInterval.setEnabled(!Start && !autoRec);
                        jCheckBox1.setEnabled(!Start && !autoRec);
                        jCBReconnect.setEnabled(!Start && !autoRec);

                        if (db != null) {
                            if (!db.getIsOpen()) {
                                jPBD.setBackground(Color.RED);
                                jPBD.setForeground(Color.WHITE);
                                jPBD.setText("ER");
                            } else {
                                jPBD.setBackground(Color.GREEN);
                                jPBD.setForeground(Color.BLACK);
                                jPBD.setText("OK ");
                            }
                        } else {
                            jPBD.setBackground(Color.RED);
                            jPBD.setForeground(Color.WHITE);
                            jPBD.setText(" ER ");
                        }


                        if (autoRec){
                            jbtnConnect.setText("Auto");
                            if (Start && Connected) {
                                jbtnConnect.setForeground(Color.BLACK);
                                jbtnConnect.setBackground(Color.GREEN);
                            } else {       
                                jbtnConnect.setForeground(Color.WHITE);
                                jbtnConnect.setBackground(Color.RED);
                            }
                        } else {
                            if (Start) {
                                jbtnConnect.setText("Disconnect");
                                jbtnConnect.setForeground(Color.BLACK);
                                jbtnConnect.setBackground(Color.GREEN);

                            } else {
                                jbtnConnect.setText("Connect");
                                jbtnConnect.setForeground(Color.WHITE);
                                jbtnConnect.setBackground(Color.RED);
                            }
                        }

                        jtfErroriCitire.setText(String.valueOf(totalErrors));
                    }
                });
                try
                {
                    Thread.sleep(300);
                    jPanel4.repaint(1);
                }
                catch (InterruptedException ex)
                {
                    Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            catch (Exception ex) {
                Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });
    updateUIThread.start();
}

I put my update UI code in run method of invokeLater. updateUI() it's called when application starts.

3
  • I'd be careful with this kind of approach, as it has the potential to flood the EDT requests, cause a degragation in the performance of the application Oct 21, 2014 at 21:34
  • it has caused something...I have 5-12% processor use (in TaskManager, under Windows 7 64bit) and something like 125-155 mb of memory use. I'll try with Swing Timers and post the results in a few days, when I'll come back from a business trip. best regards
    – serban.b
    Oct 21, 2014 at 21:57
  • "With this approach", not necessarily with this example. "This approach" "could" flood the EDT with updates, especially if those updates are fast enough or numerous enough Oct 21, 2014 at 22:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.