Swing EDT

I'm working on a project where we have problems with deadlock due to incorrectly executing code outside of the EDT. I'm just trying to understand what exactly happens when code is written incorrectly like this. Does the entire code including the painting get executed on the non-EDT thread or does the EDT ultimately try take over at some point to do the actual painting?

Thanks for the replies everyone. To get things back on topic, a couple of follow up questions
Aephyr wrote:
I'm working on a project where we have problems with deadlock due to incorrectly executing code outside of the EDT.I'm sure the execution as performed by the JVM is executing the code correctly. Maybe you mean incorrectly coded execution?
Yes you are correct.. i meant incorrectly coded execution
Also, I've been experimenting with the CheckThreadViolationRepaintManager described on [Alexander Potochkin's blog|http://weblogs.java.net/blog/alexfromsun/archive/2006/02/debugging_swing.html]. This utility provides a nice simple means of detecting coding violations of the EDT rules. I realize that the best solution is to fix any code that violates the EDT rules. However, I'm wondering if it is possible to extend this CheckThreadViolationRepaintManager beyond just detecting violations and to try 'fix' them at runtime..
e.g. something like this      public synchronized void addInvalidComponent(JComponent component) {
          if (checkThreadViolations(component)) {
               SwingUtilities.invokeLater(new EDTRunner(component, this));
          else{
               super.addInvalidComponent(component);
class EDTRunner implements Runnable {
          private JComponent component;
          private CheckThreadViolationRepaintManager repaintManager;
          public EDTRunner(JComponent component,
                    CheckThreadViolationRepaintManager repaintManager) {
               this.component = component;
               this.repaintManager = repaintManager;
          public void run() {
               repaintManager.callSuperInvalidComponent(component);
}Or at this point is it too late in the call to make it thread safe?
Edited by: oochie on Mar 17, 2010 5:04 PM

Similar Messages

  • Execute mbean methods in a separate dedicated thread.

    Hi all,
    I have an MBean and I want that all its methods be executed in swing thread. [Common swing confinement rules].
    Is there a way to do this by jmx rulebook?
    One way i though of was to use a proxy class with an inocationhandler which executes the method in the swing thread using SwingUtilities.Invokelater().
    Is there any other cleaner way?
    Thanks,

    The approach you mention looks good. An alternative is that if your MBean is a DynamicMBean then you can simply wrap it in an implementation of the DynamicMBean interface that forwards each of the five methods (excluding getMBeanInfo()) of the interface to the wrapped object, but on the Swing EDT. To avoid hassle with checked exceptions I'd be inclined to use an InvocationHandler for that too. Something like this:
    public class EDTInvocationHandler implements InvocationHandler {
        private final Object wrapped;
        public EDTInvocationHandler(Object wrapped) {
            this.wrapped = wrapped;
        public Object invoke(Object proxy, final Method m, final Object[] args) throws Throwable {
            if (m.getName().equals("getMBeanInfo"))
                return m.invoke(wrapped, args);
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    try {
                        return m.invoke(args);
                   } catch (InvocationTargetException e) {
                       ...log e.getCause()...
                   } catch (Exception e) {
                       ...log e...
        public static DynamicMBean edtDynamicMBean(DynamicMBean mbean) {
            return Proxy.newProxyInstance(
                DynamicMBean.class, DynamicMBean.class.getClassLoader(),
                new EDTInvocationHandler(mbean));
    }Depending on what you want to achieve, it might be better to use invokeAndWait, which would mean you could propagate exceptions to the caller.
    If your MBeans are Standard MBeans (or MXBeans) then you can make them into Dynamic MBeans using javax.management.StandardMBean.
    Regards,
    Éamonn McManus -- JMX Spec Lead -- [http://weblogs.java.net/blog/emcmanus]

  • SwingWorker in practice

    Sometimes ignorance seems a blessing. I really don't have any problems with my Swing application, a least not yet, until I read: "Long-running computations or input/output (I/O) bound tasks should never run on the Swing EDT." My application has plenty of database interaction, albeit no long-running tasks. However, since all network communication is potentially slow, I guess that the rule also applies to fast stored procedure calls.
    I see myself now faced with a huge amount of SwingWorker classes, one for every DAO call, for example:
    protected List<Foo> doInBackground() {
            DAOFactory fac = DAOFactory.getInstance();
            FooDAO dao = fac.getFooDAO();
            return dao.getFoos();
    }Much of my code is now concerned with SwingWorkers and adding PropertyChangeListeners to these, which make me wonder if everybody takes this rule so literally or that a more pragmatic approach will also do. In other words, do you program for the worst case or for business as usual? Perhaps there is a better way of dealing with SwingWorkers? I am looking forward to your view and experiences on this matter.

    Sometimes ignorance seems a blessing. I really don't have any problems with my Swing application, a least not yet, until I read: "Long-running computations or input/output (I/O) bound tasks should never run on the Swing EDT." My application has plenty of database interaction, albeit no long-running tasks. However, since all network communication is potentially slow, I guess that the rule also applies to fast stored procedure calls.
    I see myself now faced with a huge amount of SwingWorker classes, one for every DAO call, for example:
    protected List<Foo> doInBackground() {
            DAOFactory fac = DAOFactory.getInstance();
            FooDAO dao = fac.getFooDAO();
            return dao.getFoos();
    }Much of my code is now concerned with SwingWorkers and adding PropertyChangeListeners to these, which make me wonder if everybody takes this rule so literally or that a more pragmatic approach will also do. In other words, do you program for the worst case or for business as usual? Perhaps there is a better way of dealing with SwingWorkers? I am looking forward to your view and experiences on this matter.

  • Set wait Cursor allows cursor to Clicon on Button ?

    Sometimes when i set my cursor to wait cursor still it allows me to click on Components Like JButton or Tree node 7 sometime it works perfectly (it doesn't allow to click which i am expecting)

    I can assure you that it has nothing to do with you setting the wait cursor; you are only setting the graphic, it doesn't change the way your application behaves on mouse clicks. More likely is that "sometimes":
    1) your application is doing a lot of work
    2) it is doing this work on the Swing EDT
    3) and such your application is unresponsive, giving you the idea that you cannot click buttons
    If you want to prevent users from clicking buttons, you need to disable the buttons while you are doing whatever it is you are currently setting the wait cursor for.

  • Gui freezes during execution of a perl script which is never completed

    Dear Java programmers,
    I'm running a perl script which takes a few minutes to finish from a GUI. But when the execution reaches a point, it suddenly seems to stop and the GUI becomes irresponsive. Submitting the perl script to run as a separate thread to release the button doesn't make any different either. Is there any restriction in the time that swing allows external programs to run?
    thanks in advance,
    Tom

    tevang2 wrote:
    I'm running a perl script which takes a few minutes to finish from a GUI. But when the execution reaches a point, it suddenly seems to stop and the GUI becomes irresponsive. Then you're tying up the Swing EDT, the event dispatch thread, which is the single thread responsible for drawing the Swing app and responding to user input.
    Submitting the perl script to run as a separate thread to release the button doesn't make any different either. Is there any restriction in the time that swing allows external programs to run?None that I know of. I still have to wonder if you are creating a background thread properly because even if your perl script gets locked, if you are running it on a background thread, the Swing app shouldn't lock up.

  • Swing app keyboard stops working, mystery ESCAPE keystrokes appear in EDT

    Java 6 Swing app. In our development environment, works great. In QA, they use it for a bit, type in a text field, click out to a Windows XP/7 app, click back in the text field, and the keyboard stops accepting keystrokes. The mouse continues to work, and the Swing app continues to paint to the screen.
    I hooked up a KeyEventDispatcher to listen to what is going on. I'll post a more verbose log at the end of this post, but the short version is this. When the keyboard hangs, the log shows that 'escape' keys are being sent, though we do not do any keystroke injection in our app, ESCAPE or otherwise. Nothing on the Swing app can be determined visually to have focus.
    Just before the app starts hanging, it has a side effect of not being able to be brought into the foreground by clicking on it, if, for example, one was working with Excel or Notepad, then try to click on the JFrame title of the app, or anywhere else on the app frame/internals. Once this condition happens, moving away to another Windows app, then going back to the Swing app, causes the keyboard to stop working and the KeyEventDispatcher to see 'escape' keystrokes being sent out.
    Connecting remotely to the app via JVisualVM/JConsole does not show any of the threads hanging/blocked.
    Sometimes you can work for hours before seeing this problem, and other times, you can start the app up and it happens right away. Once it happens, sometimes you can't recover, and sometimes you can click on a button on a navigator panel on the left side that displays an info panel on the right side, and you can start typing again in text fields.
    Once this problem happens, you can start (or have already running) a completely different Swing app (ex.: StackTrace), and the keyboard will stop working for that app too, even though its running in its own separate VM.
    This problem (ALMOST!) always happen when typing in a Swing text field (JTextField, JTextArea, etc.), clicking on and then typing in a Windows text area (Excel cell, Notepad), then clicking back into the Swing app's text field. A few times, we've gotten this to happen by typing in a text field, tabbing to a button, pressing a button, then tabbing/clicking back into the text field, all without leaving the Swing app. But this latter scenario is rare, usually going to/from Swing/Windows XP/7 apps cause the problem to occur more readily.
    The QA computers normally use Citrix to connect and run the app, but this also happens if we run the app completely locally. But again, this only happens to some computers, all of the ones in the QA department; the development computers (the app has not been released into production yet) does not see this problem.
    I had thought that our problem was this problem (Wrong characters in KeyEvents generated from input of barcode scanner but purposely slowing down the acceptance of KEY_PRESSED and KEY_RELEASED events before allowing them to go on to the Swing app (via a KeyDispatcher) did not solve the problem.
    Also, we had thought it might be a Citrix problem and how it (or does it?) hook into the Windows keyboard. The fact that once one Swing app gets into this keyboard doesn't work and escape keys are being sent out by the EDT can affect another Swing app makes me wonder. We're not seeing any VM exceptions either like this (EXCEPTION_ACCESS_VIOLATION - JRE 6.0_23 - Citrix, windows 2003
    Been trying to get this one solved for over a week, but with no luck. Any help/advice would be appreciated. Thank you in advance for your time.
    P.S. Here's the detailed log info I generated via my KeyEventDispatch listener...
    2011-04-01 11:58:17,493 [AWT-EventQueue-1] DEBUG MyKeyEventDispatcher.dispatchKeyEvent:36 - KEY1-keystroke [java.awt.DefaultKeyboardFocusManager@377369]: java.awt.event.KeyEvent[KEY_PRESSED,keyCode=27,keyText=Escape,keyChar=Escape,keyLocation=KEY_LOCATION_STANDARD,rawCode=27,primaryLevelUnicode=27,scancode=1] on javax.swing.JTextField[,320,28,175x18,layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,border=com.ep.skin.lnf.framework.utils.internal.RoundedBorder@c3a7c0,flags=296,maximumSize=,minimumSize=,preferredSize=,caretColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],disabledTextColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],editable=true,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],selectionColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],columns=15,columnWidth=11,command=,horizontalAlignment=LEADING]
    2011-04-01 11:58:17,494 [AWT-EventQueue-1] DEBUG MyKeyEventDispatcher.dispatchKeyEvent:42 - KEY2-ActiveWindow: javax.swing.JFrame[mainFrame,128,128,1024x768,invalid,layout=java.awt.BorderLayout,title=My - HQ - 17601,resizable,normal,defaultCloseOperation=DO_NOTHING_ON_CLOSE,rootPane=javax.swing.JRootPane[,0,0,1024x768,invalid,layout=com.ep.skin.lnf.framework.internal.RootPaneUI$MetalRootLayout,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.BorderUIResource@d0e678,flags=16777673,maximumSize=,minimumSize=,preferredSize=],rootPaneCheckingEnabled=true]
    2011-04-01 11:58:17,496 [AWT-EventQueue-1] DEBUG MyKeyEventDispatcher.dispatchKeyEvent:48 - KEY3-CurrentFocusCycleRoot: javax.swing.JFrame[mainFrame,128,128,1024x768,invalid,layout=java.awt.BorderLayout,title=My - HQ - 17601,resizable,normal,defaultCloseOperation=DO_NOTHING_ON_CLOSE,rootPane=javax.swing.JRootPane[,0,0,1024x768,invalid,layout=com.ep.skin.lnf.framework.internal.RootPaneUI$MetalRootLayout,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.BorderUIResource@d0e678,flags=16777673,maximumSize=,minimumSize=,preferredSize=],rootPaneCheckingEnabled=true]
    2011-04-01 11:58:17,497 [AWT-EventQueue-1] DEBUG MyKeyEventDispatcher.dispatchKeyEvent:54 - KEY4-FocusedWindow: javax.swing.JFrame[mainFrame,128,128,1024x768,invalid,layout=java.awt.BorderLayout,title=My - HQ - 17601,resizable,normal,defaultCloseOperation=DO_NOTHING_ON_CLOSE,rootPane=javax.swing.JRootPane[,0,0,1024x768,invalid,layout=com.ep.skin.lnf.framework.internal.RootPaneUI$MetalRootLayout,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.BorderUIResource@d0e678,flags=16777673,maximumSize=,minimumSize=,preferredSize=],rootPaneCheckingEnabled=true]
    2011-04-01 11:58:17,498 [AWT-EventQueue-1] DEBUG MyKeyEventDispatcher.dispatchKeyEvent:60 - KEY5-FocusOwner: javax.swing.JTextField[,320,28,175x18,layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,border=com.ep.skin.lnf.framework.utils.internal.RoundedBorder@c3a7c0,flags=296,maximumSize=,minimumSize=,preferredSize=,caretColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],disabledTextColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],editable=true,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],selectionColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],columns=15,columnWidth=11,command=,horizontalAlignment=LEADING]
    2011-04-01 11:58:17,499 [AWT-EventQueue-1] DEBUG MyKeyEventDispatcher.dispatchKeyEvent:66 - KEY6-PermanentFocusOwner: javax.swing.JTextField[,320,28,175x18,layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,border=com.ep.skin.lnf.framework.utils.internal.RoundedBorder@c3a7c0,flags=296,maximumSize=,minimumSize=,preferredSize=,caretColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],disabledTextColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],editable=true,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],selectionColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],columns=15,columnWidth=11,command=,horizontalAlignment=LEADING]
    2011-04-01 11:58:17,501 [AWT-EventQueue-1] DEBUG MyKeyEventDispatcher.dispatchKeyEvent:74 - KEY7-stacktrace...
    com..client.util.MyKeyEventDispatcher$StackTraceGenerationException: This exception was created to generate a stack trace, and can be safely ignored.
         at com..client.util.MyKeyEventDispatcher.dispatchKeyEvent(MyKeyEventDispatcher.java:73)
         at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)
         at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
         at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Window.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    2011-04-01 11:58:17,504 [AWT-EventQueue-1] DEBUG MyKeyEventDispatcher.dispatchKeyEvent:36 - KEY1-keystroke [java.awt.DefaultKeyboardFocusManager@377369]: java.awt.event.KeyEvent[KEY_RELEASED,keyCode=27,keyText=Escape,keyChar=Escape,keyLocation=KEY_LOCATION_STANDARD,rawCode=27,primaryLevelUnicode=27,scancode=1] on javax.swing.JTextField[,320,28,175x18,layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,border=com.ep.skin.lnf.framework.utils.internal.RoundedBorder@c3a7c0,flags=296,maximumSize=,minimumSize=,preferredSize=,caretColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],disabledTextColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],editable=true,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],selectionColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],columns=15,columnWidth=11,command=,horizontalAlignment=LEADING]
    2011-04-01 11:58:17,506 [AWT-EventQueue-1] DEBUG MyKeyEventDispatcher.dispatchKeyEvent:42 - KEY2-ActiveWindow: javax.swing.JFrame[mainFrame,128,128,1024x768,invalid,layout=java.awt.BorderLayout,title=My - HQ - 17601,resizable,normal,defaultCloseOperation=DO_NOTHING_ON_CLOSE,rootPane=javax.swing.JRootPane[,0,0,1024x768,invalid,layout=com.ep.skin.lnf.framework.internal.RootPaneUI$MetalRootLayout,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.BorderUIResource@d0e678,flags=16777673,maximumSize=,minimumSize=,preferredSize=],rootPaneCheckingEnabled=true]
    2011-04-01 11:58:17,507 [AWT-EventQueue-1] DEBUG MyKeyEventDispatcher.dispatchKeyEvent:48 - KEY3-CurrentFocusCycleRoot: javax.swing.JFrame[mainFrame,128,128,1024x768,invalid,layout=java.awt.BorderLayout,title=My - HQ - 17601,resizable,normal,defaultCloseOperation=DO_NOTHING_ON_CLOSE,rootPane=javax.swing.JRootPane[,0,0,1024x768,invalid,layout=com.ep.skin.lnf.framework.internal.RootPaneUI$MetalRootLayout,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.BorderUIResource@d0e678,flags=16777673,maximumSize=,minimumSize=,preferredSize=],rootPaneCheckingEnabled=true]
    2011-04-01 11:58:17,508 [AWT-EventQueue-1] DEBUG MyKeyEventDispatcher.dispatchKeyEvent:54 - KEY4-FocusedWindow: javax.swing.JFrame[mainFrame,128,128,1024x768,invalid,layout=java.awt.BorderLayout,title=My - HQ - 17601,resizable,normal,defaultCloseOperation=DO_NOTHING_ON_CLOSE,rootPane=javax.swing.JRootPane[,0,0,1024x768,invalid,layout=com.ep.skin.lnf.framework.internal.RootPaneUI$MetalRootLayout,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.BorderUIResource@d0e678,flags=16777673,maximumSize=,minimumSize=,preferredSize=],rootPaneCheckingEnabled=true]
    2011-04-01 11:58:17,509 [AWT-EventQueue-1] DEBUG MyKeyEventDispatcher.dispatchKeyEvent:60 - KEY5-FocusOwner: javax.swing.JTextField[,320,28,175x18,layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,border=com.ep.skin.lnf.framework.utils.internal.RoundedBorder@c3a7c0,flags=296,maximumSize=,minimumSize=,preferredSize=,caretColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],disabledTextColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],editable=true,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],selectionColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],columns=15,columnWidth=11,command=,horizontalAlignment=LEADING]
    2011-04-01 11:58:17,510 [AWT-EventQueue-1] DEBUG MyKeyEventDispatcher.dispatchKeyEvent:66 - KEY6-PermanentFocusOwner: javax.swing.JTextField[,320,28,175x18,layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,border=com.ep.skin.lnf.framework.utils.internal.RoundedBorder@c3a7c0,flags=296,maximumSize=,minimumSize=,preferredSize=,caretColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],disabledTextColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],editable=true,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],selectionColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],columns=15,columnWidth=11,command=,horizontalAlignment=LEADING]
    2011-04-01 11:58:17,512 [AWT-EventQueue-1] DEBUG MyKeyEventDispatcher.dispatchKeyEvent:74 - KEY7-stacktrace...
    com..client.util.MyKeyEventDispatcher$StackTraceGenerationException: This exception was created to generate a stack trace, and can be safely ignored.
         at com..client.util.MyKeyEventDispatcher.dispatchKeyEvent(MyKeyEventDispatcher.java:73)
         at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)
         at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
         at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Window.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    The above log info repeats multiple times, KEY_PRESSED and KEY_RELEASE, over and over again, for 'escape' keys.
    Edited by: 850693 on Apr 7, 2011 10:16 AM (typo fix)
    Edited by: 850693 on Apr 7, 2011 10:19 AM (Fixed links)

    <discaimer>Don't put too much hope in my reply</disclaimer>
    The only real difference is QA has the Citrix client installed on them, and development does not. You don't need to run our Swing app through a Citrix client though to cause the bug/freezing, just running it on a PC with the Citrix client seems to be enough (in theory). We've been working down a checklist of possible problems/solutions, and we've gotten to the "Install Citrix to the dev PC" item now, so I'll post back if that makes a difference or not in reproducing the problem.
    I've also had QA people actually come over to a dev PC, without the Citrix client, and try to reproduce the problem, and they have not been able to. There's 'something' about their environment vs. ours, but not sure how that would manifest itself as a AWT/Swing keyboard event of mysterious escape keystrokes followed by the locking up on the keyboard, but not the whole Swing app. My personal guess is the Citirix client installing funky Windows-level keyboard driver(s), but I may be totally off on that. /shrugI read your initial post twice and couldn't find out whether you reproduce that on several different machines, so one "environmental" difference comes to mind: have you tried using another keyboard on the defective QA configuration?
    Of course that doesn't explain in itself how the problem would manifest only after switching back and forth to a native Windows app, but then, with the hint that Citrix may make a difference, maybe one driver filters out repeated "Esc" keystrokes, while another doesn't, and that manifests only after a few app switches, and the system event queue, or whatever it's called in Windows, redirects the events to the target app/window?
    Other than that, I wish you had investigated Jeanette's pacemaker hypothesis more... ;)
    Otherwise, yeah. I have a hook in to see all AWTEvent's, but I still need to see/find what's posting the mysterious escape keys to the event queue.I assume it's what you mean, but I'll try to make that clear: you have to investigate, at the OS level, what is posting escape key events to the OS queue.
    I am not a Windows developper, but I seem to understand that the following programs claims to capture keystrokes on the whole screen (not limited to a single window), with some limitations: http://www.codeproject.com/KB/winsdk/WIN_RECORDER.aspx
    More generally, you should search for a Windows way to peek at the Windows' (keyboard?) event queue.
    I'm not sure this could identify which DLL (if it's not originated by the material, see the defective keyboard hypothesis) is posting the events, but that's worth a try (Java for example, would enables to stuff a custom event queue that would trace info about a Java-poster).
    Even if you can't identify the posting DLL, running the "key captuyre" on both the Windows host that has the Citrix window, and the Windows host that you are accessing via Citrix, may give you hints as to where the heck the key strokes originate...
    Good luck, and keep us informed,
    J.

  • Accessing javax.swing.JPanel from outside the EDT

    Hi everybody!
    I am not new to Java but to Swing.
    Please consider the following:
    public class MyPanel extends JPanel
         private int number = 0;
         private Object object = null;
         public int getNumber()
              return number;
         public void setNumber(int aNumber)
              number = aNumber;
         public Object getObject()
              return object;
         public void setObject(Object aObject)
              object = aObject;
    Question:
    Is it save to call the getters and setters defined above from a Thread other than the Event Dispatching Thread.
    From my point of view and my understanding of Swing this should be save as the getters and setters do not touch anything other than the methods and instances defined within the object layer of MyPanel.
    Please help :-)

    jboeing wrote:
    I might be wrong, but I think it's safe to touch the non-Swing methods in a subclass from other threads. The main concern in accessing Swing off the EDT is that you can concurrently modify parts of code, but since the EDT does not touch your getters and setters, at least it won't make deadlocks. Perfect, exactly what I would suggest. I couldn't have put it better.
    The only oddities may occur if the member variable you set is used in logic for an overriden method (like paintComponent), but I don't think this will be too problematic in most cases.See what you mean so: What about synchronizing the getters and setters. Then only the scheduler would block the EDT as long as another Thread was touching the members. As no wait() and notify() calls arise this should not result in any deadlocks. The worst thing I could think of is that the responsiveness of the user interface may degrade if the EDT had to wait for a while as to many Threads were already waiting for synchronized accesss.
    >
    Edit:
    Oh, and in the future, use the "*Code Formatting Tags*", see http://forum.java.sun.com/help.jspa?sec=formatting
    Edited by: jboeing on Nov 13, 2007 1:14 PM
    public class Apology{
        public static void main(String[] args){
            System.out.println("Thank you for your kind advice :-)");
            System.out.println("but please don't ask me why this is quoted style");
    }Edited by: tog on Nov 14, 2007 6:08 PM

  • Keeping Swing calls on the EDT, app code off the EDT, and boilerplate code

    I have been reading about the EDT and Swing for a while now and I have not been able to find very good tutorials or explanations. I understand that swing calls should be on the EDT and I have seen hints about application code needing to be on its own thread, which seems obvious. I have seen code for how to do this, but it seems like in order to really enforce these rules, I'd have to setup invoke SwingUtilities.invokeLater on all my swing related functions (I have a ton of them), and then for non-swing related functions, I'd have to constantly check to make sure they are not on the EDT with javax.swing.SwingUtilities.isEventDispatchThread?

    BoBear2681 wrote:
    Also keep in mind that many very quick non-UI tasks can safely be done on the EDT. For example, if you load a very small text file (a few KB), this is usually so fast that there's no need to do it off the EDT. Just pointing out that not literally everything needs to be done off the EDT, just anything that runs long enough to produce a noticeable unresponsive pause in your GUI. Users are okay with an application taking 0.1 seconds to open a file, for example. But doing 10 seconds of number crunching, connecting to a remote server, etc. are the kinds of things you'd want to do off the EDT.That's extremely true, and I meant to touch on that but forgot (yep, my memory is so bad that I forget what I was going to type in the amount of time it takes to post a reply).
    When I first started to figure out the EDT, I became paranoid about keeping non-GUI stuff off of it. However, I've since realized that sometimes it's unavoidable, and usually it doesn't matter anyway.

  • Swing, Animation and EDT

    I am developing an application where I have a JPanel and custom components (by this I mean I am extending JLabel). These custom components are added to the JPanel and I would like them to animate when they receive a command.
    As each component may receive the same messages and therefore may wish to animate at the same time I have created Runnable objects and these are added to the EventQueue when required. Each custom component is implemented as follows:
    public class CustomRobot extends JLabel implements CANListener {
        //variable declarations and attributes
        //overriding paincomponent
       public void paintComponent(Graphics g){
           super.paintComponent(g);
           2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                         RenderingHints.VALUE_ANTIALIAS_ON);  
           g2.rotate(rotationDegree, getWidth()/2-5, getHeight()/2);
           g2.draw(robInUpper);
           g2.draw(robInGripperR);
           g2.draw(robInGripperL);
           g2.draw(robotPlatform);
        //This method is fired when a message is received by the CANListener
        //Similar to actionPerformed() from ActionListener
        public void onMessage(Message message) {
            try {
             if (message instanceof TextMessage) {
             TextMessage tm = (TextMessage) message;
                if (tm.getText().startsWith("0x0a")){
              EventQueue.invokeLater(pickup);
            } catch (Exception ex) {
              System.err.println(ex.getMessage());
           Runnable pickup = new Runnable(){
             public void run(){
              while(Math.toDegrees(rotationDegree) < 90){
                   rotationDegree += rotationTheta;
                   System.out.println(Math.toDegrees(rotationDegree));
                    try { Thread.sleep(100); } catch (Exception e) { 
                                        System.out.println("Error"); }
                    repaint();
    The problem is that the component will only repaint when it gets to 90 degrees, it does not animate. Am I going about this totally wrong? I have the feeling that maybe it is because I am trying to animate the component from within itself rather than in a different class.
    Any help would be greatly appreciated.
    Thanks!

    Am I going about this totally wrong?You are telling the EDT to sleep. If it sleeps then it can't receive events or repaint the GUI. Using a separate Thread is one solution for removing long running code from the EDT. And telling another Thread to sleep will not affect the EDT.
    However if you want animation then use a [url http://java.sun.com/docs/books/tutorial/uiswing/misc/timer.html]Swing Timer. The timer simply fires an event every "x" ms and you can then tell your component to repaint itself.

  • [ADF-swing] ViewObject blocks EDT, how to work around?

    I'm working with JDeveloper 11.1.1.5.
    I have a query-based VO that takes a long time to execute.
    While the Statement runs I want to show a Waiting Dialog showing an animated GIF so that the user knows the application is working and not hung.
    When I do the query directly then my WaitingDialog shows the Animation as expected. The following runs in a thread of ist own:
    ViewObject viewObject = myApplicationModule.findViewObject("MyViewObjectsName");
    PreparedStatement s = ((DBTransaction)_am.getTransaction()).createPreparedStatement(viewObject.getQuery(),0);
    try{
      s.executeQuery();
    }(catch SQLException ex){
    ex.printStacktrace();
    when I Change this to execute the vo instead the Dialog hangs:
    ViewObject viewObject = myApplicationModule.findViewObject("MyViewObjectsName");
    viewObject.executeQuery();
    how do I configure ADF so that it does not block EDT?
    bye
    TPD

    An alternative method for the UI is to use the radio buttons control. You can customize the standard one to use the square buttons, and I believe this would give you the equivalent effect that you're doing with the lights. See attached VI along with customized control. For the customized control I took a standard radio button control, opened it for editing, and replaced the circular booleans with square buttons. The radio button control is an enumeration, with the enumeration items being the labels of the individual controls (not the text inside the buttons). The control is set so that the labels on the individual square buttons is not visible.
    Attachments:
    Event Structure Example2.vi ‏45 KB
    Control 1.ctl ‏6 KB

  • Can i CREATE Swing objects from without EDT?

    Subj
    Thenx.

    Yes, you can create Swing components and set their properties in any thread as long as the component hasn't been realized yet (by calling pack or setVisible on its parent).

  • Swing and Active rendering problem

    Hopefully this is the right place to post. I have a problem with active rendering and swing. Basically my code below messes up when I start rendering the swing either using repaint() or paint(g).
    If I use repaint() then the gui flickers like mad and if I use paint(g) then I get deadlocks when typing into the textbox.
    Any help would be great for what am I doing wrong. How do I solve this problem?
    public GuiWindow() {
              try {
                   guiImage = ImageIO.read(this.getClass().getResource("Images/Gui2.png"));
              } catch (Exception e) {}
              this.setPreferredSize(new Dimension(800, 600));
              this.setUndecorated(true);
              this.setIgnoreRepaint(true);
              this.setResizable(false);
              this.addKeyListener(kl);
              this.setFocusable(true);
              this.requestFocus();
              this.setTitle("PWO");
              JPanel panel = new JPanel()
              public void paintComponent(Graphics g)
              //Scale image to size of component
                   super.paintComponent(g);
                   Dimension d = getSize();
                   g.drawImage(guiImage, 0, 0, d.width, d.height, null);
                   this.setIgnoreRepaint(true);
                            //draw background for the gui
              JTextField Name = new JTextField(20);
              panel.add(Name);
              this.setContentPane(panel);
                    myRenderingLoop();
    public void myRenderingLoop() {
              int fps = 20;
              long startTime;
              int frameDelay = 1000 / fps;
              this.createBufferStrategy(2);
              BufferStrategy myStrategy = this.getBufferStrategy();
              Graphics2D g;
              while (!done) {
                   startTime = System.currentTimeMillis();          
                   do {
                        do {
                             g = (Graphics2D)myStrategy.getDrawGraphics();
                             this.repaint();
                             this.render(g); //render the game
                             g.dispose();
                        } while (myStrategy.contentsRestored());
                        myStrategy.show();
                        Toolkit.getDefaultToolkit().sync();
                   } while (myStrategy.contentsLost());
                   while (System.currentTimeMillis() - startTime < frameDelay) {
                        try {
                             Thread.sleep(15);
                        } catch (InterruptedException ex){}
         }Edited by: Aammbi on Apr 6, 2008 7:05 PM

    I really have no idea what your code is trying to do, but a few comments.
    1) There is no need to use a BufferStrategy since Swing is double buffered automatically
    2) Don't use a while loop with a Thread.sleep(). Chances are the GUI EDT is sleeping which makes the GUI unresponsive
    3) Use a Swing Timer for animation.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.

  • RMI callbacks to Swing

    Hi! I'm serious need of some help. I have a Swing application that is also a remote object that, asynchronously, receives callbacks from other remote objects. Those callbacks are intended to update several components of my swing application (like JTree, JTextArea and JEditorPane) but they don't...! I do receive the callbacks but they just don't seem to update the components. I'm using the EDT but it still doesn't work! I guess i'm not using the EDT correctly but i just can't figure out how. From what i've read, it should be quite simple.
    Can someone help? :|
    Carlos
    PS: here goes some of the code.
        public synchronized void receiveNotification(final Notification n, final int notificationId) throws RemoteException {
            Runnable receiveNotification = new Runnable() {
                public void run() {
                    if (notificationId == reportId) {
                        addToStatus("Received Report from " + n.getAgentId() + ".");
                        addReportToTree(n);
                    else if (notificationId == traceId) {
                        addToStatus("Received Trace from " + n.getAgentId() + ".");
                        addTraceToTree(n);
            SwingUtilities.invokeLater(receiveNotification);
        private void addToStatus(final String status) {
            ensureEventThread();
            errorArea.append("\n" + status + "\n");
        }

    The problem may be in how you're updating. You should post the code to addReportToTree() and addTraceToTree(). Is it safe to assume the NotificationId values received are correct to trigger updates?
    Cheers
    DB

  • Threads + Swing = Confusion

    Hi all,
    I am having a problem with threads and Swing apps. I have read the tutorial 3 times and get more confused each time i try to understand how to update the gui with the other thread.
    At this point I'm just trying to do something simple (eventually i want the gui to report all the progress of the action): get a progress bar to be updated through a Thread Class. I have the gui built with a button and a progress bar. Here is the codei have for the simpleThread class
    import java.awt.*;
    import javax.swing.*;
    public class simpleThread extends Thread{
        public simpleThread(String str) {
            super(str);
        public void run() {
            for (int i = 0; i<1000000; i++) {
                final int x = i;
                Runnable getTextFieldText = new Runnable() {
                    public void run() {
                       jProgressBar1.setValue(x);
        SwingUtilities.invokeAndWait(getTextFieldText);
    }The problem i have is that the thread doesn't recognize the gui form. Any help on getting the progress bar to update with the thread would be great! Thanks! :)

    There's been too much bad code submitted to this topic to comment on it individually, but:
    1. Don't call a thread or runnable's run() method directly, if you expect it to be executed in a different thread! Call thread's start method instead.
    2. If you want code executed in the Event Dispatch Thread (EDT), pass a runnable to InvokeLater (usually preferrable to InvokeAndWait). That runnable's run method will be executed in the EDT -- there's no need to write complicated nested run methods!
    In the case of JProgressBar, I was concerned about flooding the EDT with many "invokeLater" runnables, so I penned this wee class:
    import javax.swing.*;
    public class Updater  {
         private final JProgressBar jpb;
         private boolean queued;
         private int val;
         private Runnable runnable = new Runnable() {
              public void run() {//called from EDT:
                   int _val;
                   synchronized(Updater.this) {
                        queued = false;
                        _val = val;
                   jpb.setValue(_val);
         public Updater(JProgressBar jpb) {
              this.jpb = jpb;
         public void update(int _val) {
              boolean go = false;
              synchronized(this) {
                   val = _val;
                   if (!queued) {
                        queued = true;
                        go = true;
              if (go)
                   SwingUtilities.invokeLater(runnable);
    }To use it, you would typically declare it as a field:
    private Updater updater = new Updater(yerBar);Then repeatedly call (from any thread)
    updater.update(yerValue);

  • Setting-up a class of swing objects - how to?

    I'm interested in creating a class that contains several swing objects. What is a good location to initialize the swing objects? I'd appreciate some options other than the constructor (events?), or why this is a good location? Also, as a secondary question, should I wrap the swing code in a swing thread or assume the caller will do this?
    class manyJObjects extends javax.swing.JLayeredPane {
        javax.swing.JTextArea txtArea;
        manyJObjects(){
        //Ensure we are in a swing thread then call drawDisplay()
            if(javax.swing.SwingUtilities.isEventDispatchThread()){
                drawDisplay();
            } else {
                try {
                    java.awt.EventQueue.invokeAndWait(new Runnable() {               
                    public void run() {
                        drawDisplay();
                } catch (InterruptedException ie) {
                } catch (InvocationTargetException ite) {
        void drawDisplay(){
        //In the actual there were be more swing objects
            try{
                txtArea = new javax.swing.JTextArea();
                javax.swing.SpringLayout spring = new javax.swing.SpringLayout();
                this.setLayout(spring);
                this.add(txtArea);
                spring.putConstraint(SpringLayout.NORTH, txtArea, 0, SpringLayout.NORTH, this);
                spring.putConstraint(SpringLayout.EAST, txtArea, 0, SpringLayout.EAST, this);
                spring.putConstraint(SpringLayout.SOUTH, txtArea, 0, SpringLayout.SOUTH, this);
                spring.putConstraint(SpringLayout.WEST, txtArea, 0, SpringLayout.WEST, this);
            } catch(Exception e) {
    }

    It's perfectly fine to initialize Swing components in the constructor, even if the constructor is called in a non-EDT thread. As long as the components have not been realized (i.e. pack() or setVisible(true)) then it's safe to set them up in a dedicated non-EDT thread. However, after the components have been realized, that's when you should only access/modify them via the EDT.
    public static int main(String[] args) {
         MyFrame frame = new MyFrame(); // Constructor can do anything it wants to the Swing components except call pack() or setVisible(true).
         frame.setVisible(true);
         // After this the frame and all child components have been "realized", so the Swing thread-safety rules apply now.
    }

Maybe you are looking for

  • How can I remove all the drawing canvases from a Word file?

    Hi, There are many drawing canvases in the document, which were created by pressing 'edit' on embedded EMF files. I would like to replace the embedded figures with object references, so I searched for a way to delete all the drawing canvases but coul

  • What tools should I use for Oracle Quoting enhancement?

    Hi, My company is using Oracle Application 11i (EBS) 11.5.10. We want to do a small enhancement on Oracle Quoting (HTML not Oracle Form). What tools and which version should I use? Thanks! Phil

  • Reg SAP HCM Process Change Position Attributes

    Hi All, I have copied the standard Form Scenario 'S_HR_PD_CHANGE_POS_ATTRIBUTES' into Custom one. I have made only one step i.e. Stage02 (Process) and attached everything ISR Scenario,Form,Interfaces. I have created one process and attached the form

  • Force VC to use updated WSDL WebService - URGENT

    Hello, I published a WSDL directly via logical destinations in NWA. Doing a Task->Search in VC does not updated the operations. After a full reboot, VC finds all new operations, so it seems it updated the WSDL. However, some operations (with new inte

  • Syncing freeze

    First time trying to Sync my new iPhone and I can't get passed backup, less than a minute in it appears to freeze. Nothing happens, even after several hours.