Executing Code outside of the Event Dispatcher Thread

Hello,
I have just come to learn that any actionPerformed() method that is called after an event occurs actually runs in the Event Dispatcher. So, for example, if you click on a button, any code that is run as a result is run in the event dispatcher.
So there are two things I am wondering about. First, If i run code in response to a user event, then it doesn't have to use invokeLater() to update GUI components because it's already being run in the event thread? Second, if I run code in response to an event but it's computationally expensive and I do not want to run it in the Event Dispatcher thread, how do i do that? Will a method call cause it to do so, or do i have to specifically create a new thread for it?
My questions are a result of this: How does one normally go about updating a GUI during a long process? I figured that if I could get the process to run in any thread other than the Event Dispatcher, I could call invokeLater() within it and it would update the GUI. Am I correct in assuming so?

So there are two things I am wondering about. First, If i run code in response to a user event, then it doesn't have to use invokeLater() to update GUI components because it's already being run in the event thread?
Correct. So if your response to an action is, for example, creating a new bit of UI using data which is already in memory, you can just do it.
Second, if I run code in response to an event but it's computationally expensive and I do not want to run it in the Event Dispatcher thread, how do i do that? Will a method call cause it to do so, or do i have to specifically create a new thread for it?
You will need to create a new thread: method calls are just control flow within the same thread.
You should use an object which implements Runnable and then use "new Thread(foo).start()"
My questions are a result of this: How does one normally go about updating a GUI during a long process?
You have to hop back onto the EDT whenever an update is required. I'd suggest writing yourself a little reusable class or two to help you with this - such as a listener mechanism with an implementation which handles the thread hopping.
I figured that if I could get the process to run in any thread other than the Event Dispatcher, I could call invokeLater() within it and it would update the GUI. Am I correct in assuming so?
Yes.
Should I use inner classes? I would prefer to keep them as separate classes within the same package.
Depends on all sorts of things - sometimes anonymous or declared inner objects are the way forward, sometimes public class objects, sometimes generic helper objects and sometimes utility classes. There are all sorts of different scenarios. As I say, though, it's worth writing some utility/helper classes to reuse. Personally I don't find SwingWorker is ideal so I have my own. Note that an abstract Action implementation is a very useful one, since this is precisely where you need to be doing most of the thread hopping.

Similar Messages

  • ..this method should be invoked from the event-dispatching thread?

    I see this (the title that is) in every single Java demo/example program on this (Sun's) site. However, I just tend to
    public static void main(String[] args){
       new whateverTheClassIsCalled();
    }And I've seen this approach on other sites and other example programs.
    So what exactly is better about this;
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
        }where createAndShowGUI() sets and packs the frame. I just do all this in the class constructor (when it's a JFrame!)
    So what does all this thread dispatching stuff mean, why should I use it etc etc.
    tia.

    Is it just me? For some reason it rubs me the wrong way that swing isn't thread safe. From what I've read, my understanding is that its safe to modify swing components from other threads as long as they haven't asked to be painted. If you don't do paint(), pack() or setVisible(true) until the end of your initialization, you will be safe.
    The reason for not being thread safe is almost certainly performance. Swing is slow enough as it is. Since the vast majority of Swing activity takes place in response to events and thus is on the EDT, there usually isn't a problem.
    This is a serious nuisance in network and database programs where multiple threads are used. I end up using invokeLater a lot in those cases, but never for initialization. Sun has only started to recomment that recently.
    Note that the fireXXX methods do not put the event on the EDT, these simply create Event objects and send them to Listeners. If they are executed off the EDT the Listeners will get called off the EDT.

  • Not Running on the Event Dispatch thread, but UI still freezes

    The environment: I am currently working on an application that requires some heavy lifting in response to user input on a UI. To do this I am using a version of SwingWorker that was backported from java 1.6 to java 1.5 in conjunction with a slew of custom threads.
    The problem: I am currently running into an issue where I am not operating on the Event Dispatch thread (checked by doing a javax.swing.SwingUtilities.isEventDispatchThread()) but the UI is still freezing during this section. The operation involves a loop with about 2000 iterations and contains several file accesses. I have thought about how to make a new thread to perform the same operation, but I do not see how it would be any different since as it is I am not on the EDT. The call is being made from doInBackground and specifically the piece that is slowing things down is the File Accesses (2 for every iteration of the loop). At this point I am not sure how to go about resolving the issue. Any one have any suggestions?

    I am not operating on the Event Dispatch threadThat is the problem. Use multiple threads for GUI, which should delegates to the EDT, and your app logic.

  • CODE TRICK: event dispatch thread and tables

    This is a handy little trick for all you MVC users out there...
    I was working on a table class and I had this little issue that came up about not calling the AbstractTableModel's update (fireXxx()) methods from outside the event dispatch thread.
    As I'm one to create my own table models anyway, to match my data source, I found this little trick, with a little help from java.awt.EventQueue, works nicely to let the method be called from any place without having to worry about what thread it's in. Seems to work well...
         * Overridden to make safe when calling from the event dispatch thread
         * or another thread.
         * @see javax.swing.table.AbstractTableModel#fireTableRowsUpdated(int, int)
        public void fireTableRowsUpdated(final int firstRow, final int lastRow)
            if(EventQueue.isDispatchThread())
                super.fireTableRowsUpdated(firstRow, lastRow);
            else
                try
                    // could use invokeLater, depending on your needs
                    SwingUtilities.invokeAndWait(new Runnable() {
                        public void run()
                            MyTableModel.super.fireTableRowsUpdated(firstRow, lastRow);
                catch (Exception e)
                    e.printStackTrace();
        }

    http://java.sun.com/products/jfc/tsc/articles/timer/index.html

  • Event Dispatch Thread Hangs, what is wrong?

    The Event Dispatch Thread Hangs when showing a modal dialog while running a
    SwingWorker Thread.
    I have included my code at the bottom of the page. There are three classes. I have posted a bug report to red hat. But I want to make sure my code is correct.
    My test case just puts the SwingWorker to sleep
    but the problem occurs if I do something real, like connect to a database, etc.
    Also I have tried little different variations of the logic calling
    setVisible(true)/(false) in different places and the same problem occurs.
    It seems to work with Sun JDK, note I am using IcedTea with Fedora Core 8.
    Version-Release number of selected component (if applicable):
    [szakrews@tuxtel ~]$ java -version
    java version "1.7.0"
    IcedTea Runtime Environment (build 1.7.0-b21)
    IcedTea Client VM (build 1.7.0-b21, mixed mode)How reproducible:
    Every couple times.
    javac TestClass2
    java TestClass2eventually it will hang. If it doesn't try again.
    You don't have to wait for the program to finish either.
    The program runs the Dialog 10 times but it never works or fails in the middle, it will either work or fail from the first dialog displayed.
    I have included a thread dump. That is about the most informative information I can get. Neither tracing nor writing a custom ThreadQueue or Drawing Manager to trace events produces any helpful information.
    Actual results:
    The JProccessBar won't move, and the SwingWorker finishes but the done() method is never run. The PROGRAM is not hung however because if I close the dialog then it will continue.
    Expected results:
    The JProccessBar should always move and the SwingWorker should always run the done() method.
    Additional info:
    java thread dump after freeze, taken with kill -s SIGQUIT <pid>
    2008-06-25 12:25:50
    Full thread dump IcedTea Client VM (1.7.0-b21 mixed mode):
    "DestroyJavaVM" prio=10 tid=0x938afc00 nid=0x1419 waiting on condition
    [0x00000000..0x0018a074]
       java.lang.Thread.State: RUNNABLE
    "AWT-EventQueue-0" prio=10 tid=0x938ae400 nid=0x1429 in Object.wait()
    [0x07f96000..0x07f96f04]
       java.lang.Thread.State: WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            - waiting on <0x96748f80> (a java.awt.EventQueue)
            at java.lang.Object.wait(Object.java:503)
            at java.awt.EventQueue.getNextEvent(EventQueue.java:485)
            - locked <0x96748f80> (a java.awt.EventQueue)
            at
    java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:248)
            at
    java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:201)
            at
    java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:195)
            at java.awt.Dialog$1.run(Dialog.java:1073)
            at java.awt.Dialog$3.run(Dialog.java:1127)
            at java.security.AccessController.doPrivileged(Native Method)
            at java.awt.Dialog.show(Dialog.java:1125)
            at java.awt.Component.show(Component.java:1456)
            at java.awt.Component.setVisible(Component.java:1408)
            at java.awt.Window.setVisible(Window.java:871)
            at java.awt.Dialog.setVisible(Dialog.java:1012)
            at net.xtel.production.WaitDialog.showWaitDialog(WaitDialog.java:72)
            at net.xtel.production.WaitDialog.showWaitDialog(WaitDialog.java:102)
            at TestClass2.showWait(TestClass2.java:79)
            at TestClass2.createAndShowGUI(TestClass2.java:126)
            at TestClass2.access$0(TestClass2.java:114)
            at TestClass2$3.run(TestClass2.java:138)
            at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:227)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:603)
            at
    java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:276)
            at
    java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:201)
            at
    java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:191)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:186)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:178)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:139)
    "AWT-Shutdown" prio=10 tid=0x938ad000 nid=0x1428 in Object.wait()
    [0x03ea7000..0x03ea7f84]
       java.lang.Thread.State: WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            - waiting on <0x96749268> (a java.lang.Object)
            at java.lang.Object.wait(Object.java:503)
            at sun.awt.AWTAutoShutdown.run(AWTAutoShutdown.java:281)
            - locked <0x96749268> (a java.lang.Object)
            at java.lang.Thread.run(Thread.java:675)
    "AWT-XAWT" daemon prio=10 tid=0x938a8400 nid=0x1423 runnable
    [0x02ccc000..0x02ccd104]
       java.lang.Thread.State: RUNNABLE
            at sun.awt.X11.XToolkit.waitForEvents(Native Method)
            at sun.awt.X11.XToolkit.run(XToolkit.java:550)
            at sun.awt.X11.XToolkit.run(XToolkit.java:525)
            at java.lang.Thread.run(Thread.java:675)
    "Java2D Disposer" daemon prio=10 tid=0x93854000 nid=0x1421 in Object.wait()
    [0x07aea000..0x07aead84]
       java.lang.Thread.State: WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            - waiting on <0x966e7010> (a java.lang.ref.ReferenceQueue$Lock)
            at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:134)
            - locked <0x966e7010> (a java.lang.ref.ReferenceQueue$Lock)
            at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:150)
            at sun.java2d.Disposer.run(Disposer.java:143)
            at java.lang.Thread.run(Thread.java:675)
    "Low Memory Detector" daemon prio=10 tid=0x93c15000 nid=0x141f runnable
    [0x00000000..0x00000000]
       java.lang.Thread.State: RUNNABLE
    "CompilerThread0" daemon prio=10 tid=0x93c13400 nid=0x141e waiting on condition
    [0x00000000..0x03a8a954]
       java.lang.Thread.State: RUNNABLE
    "Signal Dispatcher" daemon prio=10 tid=0x93c11c00 nid=0x141d waiting on
    condition [0x00000000..0x00000000]
       java.lang.Thread.State: RUNNABLE
    "Finalizer" daemon prio=10 tid=0x095e7000 nid=0x141c in Object.wait()
    [0x005d2000..0x005d3004]
       java.lang.Thread.State: WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            - waiting on <0x966e71d8> (a java.lang.ref.ReferenceQueue$Lock)
            at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:134)
            - locked <0x966e71d8> (a java.lang.ref.ReferenceQueue$Lock)
            at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:150)
            at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:177)
    "Reference Handler" daemon prio=10 tid=0x095e2400 nid=0x141b in Object.wait()
    [0x00581000..0x00582084]
       java.lang.Thread.State: WAITING (on object monitor)
            at java.lang.Object.wait(Native Method)
            - waiting on <0x966e7260> (a java.lang.ref.Reference$Lock)
            at java.lang.Object.wait(Object.java:503)
            at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:134)
            - locked <0x966e7260> (a java.lang.ref.Reference$Lock)
    "VM Thread" prio=10 tid=0x095dec00 nid=0x141a runnable
    "VM Periodic Task Thread" prio=10 tid=0x93c17400 nid=0x1420 waiting on condition
    JNI global references: 836
    Heap
    def new generation   total 960K, used 152K [0x93f40000, 0x94040000, 0x966a0000)
      eden space 896K,   9% used [0x93f40000, 0x93f56148, 0x94020000)
      from space 64K, 100% used [0x94020000, 0x94030000, 0x94030000)
      to   space 64K,   0% used [0x94030000, 0x94030000, 0x94040000)
    tenured generation   total 4096K, used 1088K [0x966a0000, 0x96aa0000, 0xb3f40000)
       the space 4096K,  26% used [0x966a0000, 0x967b01b0, 0x967b0200, 0x96aa0000)
    compacting perm gen  total 12288K, used 9169K [0xb3f40000, 0xb4b40000, 0xb7f40000)
       the space 12288K,  74% used [0xb3f40000, 0xb4834740, 0xb4834800, 0xb4b40000)
    No shared spaces configured.CLASS1:
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.sql.SQLException;
    import java.util.concurrent.ExecutionException;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.RepaintManager;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    public class TestClass2 extends JFrame implements ActionListener {
            /** Action Command for <code>searchbtn</code> */
            public static final String SEARCH_BTN_ACTION = "search_btn_action";
             * Constructor.
            public TestClass2() {
                    setSize(650, 350);
                    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                    setLocation(screenSize.width / 2 - getSize().width / 2,
                                    screenSize.height / 2 - getSize().height / 2);
                    setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                    addWindowListener(new WindowAdapter() {
                            @Override
                            public void windowClosing(WindowEvent e) {
                                    exit();
                    JPanel panel = new JPanel();
                    add(panel);
                    setVisible(true);
            @Override
            public void actionPerformed(ActionEvent e) {
                    if (e.getActionCommand().equals(SEARCH_BTN_ACTION)) {
                            JOptionPane.showMessageDialog(this, "Button Pressed");
            public void showWait() {
                    try {
                            WaitDialog.showWaitDialog(this, "Testing...", new SwingWorkerInterface(){
                                    @Override
                                    public Object workToDo() throws Throwable {
                                            Thread.currentThread().sleep(3000);
                                            return null;
                    } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                    } catch (ExecutionException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
             * Exits the program.
            public void exit(){
                    System.exit(0);
             * Create the GUI and show it. For thread safety, this method should be
             * invoked from the event-dispatching thread.
             * @throws UnsupportedLookAndFeelException
             * @throws IllegalAccessException
             * @throws InstantiationException
             * @throws ClassNotFoundException
             * @throws NullInstanceVariableException
             * @throws SQLException
            private static void createAndShowGUI() {
                    // set look and feel
                    try{
                            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                            // Create instance of the ProductCatalog
                            TestClass2 root = new TestClass2();
                            for(int i = 0; i < 10; i++){
                                    root.showWait();
                    }catch(Exception e){
                            e.printStackTrace();
             * @param args
             *            this program does not use arguments
            public static void main(String[] args) {
                    SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                    createAndShowGUI();
    }CLASS 2:
    import java.awt.Component;
    import java.awt.Frame;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.util.concurrent.ExecutionException;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JProgressBar;
    import javax.swing.SwingWorker;
    public class WaitDialog extends JDialog {
            private boolean disposed = false;
            private boolean displayed = false;
            private WorkerThread worker = null;
            WaitDialog(Frame parent, String text, SwingWorkerInterface in){
                    super(parent, true);
                    worker = new WorkerThread(in);
                    setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                    addWindowListener(new WindowAdapter() {
                            @Override
                            public void windowOpened(WindowEvent e) {
                                    worker.execute();
                            @Override
                            public void windowClosing(WindowEvent e) {
                                    disposeWaitDialog();
                    this.setResizable(false);
                    JLabel message = new JLabel();
                    message.setText(text);
                    JProgressBar pb = new JProgressBar();
                    pb.setIndeterminate(true);
                    // set size and location
                    setSize(200, 100);
                    setLocationRelativeTo(parent);
                    JPanel panel = new JPanel();
                    panel.add(message);
                    panel.add(pb);
                    add(panel);
            public void showWaitDialog(){
                    if(displayed == true){
                            return;
                    if(disposed == true){
                            disposed = false;
                            return;
                    disposed = false;
                    displayed = true;
                    setVisible(true);
            public void disposeWaitDialog(){
                    if(disposed == true){
                            return;
                    if(displayed == true){
                            displayed = false;
                            setVisible(false);
                            return;
                    disposed = true;
                    displayed = false;
            public static Object showWaitDialog(Component parent, String text, SwingWorkerInterface in) throws InterruptedException, ExecutionException {
                    WaitDialog waitDialog = null;
                    if (parent == null) {
                            waitDialog = new WaitDialog(JOptionPane.getRootFrame(), text, in);
                    } else {
                            waitDialog = new WaitDialog(JOptionPane.getFrameForComponent(parent), text, in);
                    while(!waitDialog.worker.isDone()){
                            System.out.println("about to show");
                            waitDialog.showWaitDialog();
                            System.out.println("done showing");
                    waitDialog.dispose();
                    return waitDialog.worker.get();
            class WorkerThread extends SwingWorker<Throwable, Void> {
                    private SwingWorkerInterface in = null;
                    WorkerThread(SwingWorkerInterface in){
                            this.in = in;
                    public Throwable doInBackground(){
                                    try {
                                            System.out.println("about to do work");
                                            in.workToDo();
                                            System.out.println("done work no exception");
                                    } catch (Throwable e) {
                                            System.out.println("done work with exception");
                                            return e;
                                    return null;
                    public void done(){
                                    System.out.println("about to dispose");
                                    disposeWaitDialog();
                                    System.out.println("disposed");
    }CLASS 3:
    public interface SwingWorkerInterface {
            public Object workToDo() throws Throwable;
    }

    There's nothing directly wrong with it, but it will
    prevent other threads acquiring the class lock - but
    that may be what you want.True. Although the typical case for code that looks like this would be to use wait--usually the various threads in question require the same lock, so you have to use wait in order for the waiting thread to give it up and allow the other thread to do its work. Hard to say for sure though what he's doing.
    Also, if loading is all that the other thread does, and you're waiting for that thread to die, use join. But then, if that's the case, and you're only waiting for a single other thread, then you might as well just put it all in one thread, as already indicated.

  • Using JOptionPane in a non-event dispatching thread

    I am currently working on a screen that will need to called and displayed from a non-event dispatching thread. This dialog will also capture a user's selection and then use that information for later processing. Therefore, the dialog will need to halt the current thread until the user responds.
    To start, I tried using the JOptionPane.showInputDialog() method and set the options to a couple of objects. JOptionPane worked as advertised. It placed the objects into a combobox and allowed the user to select one of them. However, it also gave me something unexpected. It actually paused the non-event handling thread until the user had made a selection. This was done without the JOptionPane code being wrapped in a SwingUtilities.invokeLater() or some other device that would force it to be launched from an Event Handling Thread.
    Encouraged, I proceeded to use JOptionPane.showInputDialog() substituting the "message" Object with a fairly complex panel (JRadioButtons, JLists, JTextFields, etc.) that would display all of the variety of choices for the user. Now, when the screen pops up, it doesn't paint correctly (like what commonly occurs when try to perform a GUI update from a non-event dispatching thread) and the original thread continues without waiting for a user selection (which could be made if the screen painted correctly).
    So, here come the questions:
    1) Is what I am trying to do possible? Is it possible to create a fairly complex GUI panel and use it in one of the static JOptionPane.showXXXDialog() methods?
    2) If I can't use JOptionPane for this, should I be able to use JDialog to perform the same type function?
    3) If I can use JDialog or JFrame and get the threading done properly, how do I get the original thread to wait for the user to make a selection before proceeding?
    I have been working with Java and Swing for about 7-8 years and have done some fairly complex GUIs, but for some reason, I am stumped here. Any help would be appreciated.
    Thanks.

    This seems wierd that it is functioning this way. Generally, this is what is supposed to happen. If you call a JOptionPane.show... from the Event Dispatch Thread, the JOptionPane will actually begin processing events that normally the Event Dispatch Thread would handle. It does this until the user selects on options.
    If you call it from another thread, it uses the standard wait and notify.
    It could be that you are using showInputDialog for this, try showMessageDialog and see if that works. I believe showInputDialog is generally used for a single JTextField and JLabel.

  • Two Event Dispatch threads?

    I took a core dump of my swing app and it shows 2 threads in the following name (*AWT-EventQueue-0, AWT-EventQueue-1*). When does this happen? I know there could be only one Event dispatch thread. Please clarify! Tks
    name: AWT-EventQueue-1 id: 155 daemon: false alive: true priority: 6 state: WAITING thread group: java.lang.ThreadGroup[name=javawsSecurityThreadGroup,maxpri=10]
    stack trace:
    [java.lang.Object.wait(Native Method), java.lang.Object.wait(Object.java:485), java.awt.EventQueue.getNextEvent(Unknown Source), java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source), java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source), java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source), java.awt.EventDispatchThread.pumpEvents(Unknown Source), java.awt.EventDispatchThread.pumpEvents(Unknown Source), java.awt.EventDispatchThread.run(Unknown Source)]
    name: AWT-EventQueue-0 id: 29 daemon: false alive: true priority: 6 state: TIMED_WAITING thread group: java.lang.ThreadGroup[name=main,maxpri=10]
    stack trace:
    [java.lang.Object.wait(Native Method), com.lb.stomp.tiger.gui.Level2View.setClientMode(Level2View.java:87), com.lb.stomp.tiger.gui.Level2View.doClientModeRefresh(Level2View.java:302), com.lb.stomp.tiger.gui.Level2View.access$100(Level2View.java:44), com.lb.stomp.tiger.gui.Level2View$4.run(Level2View.java:291), java.awt.event.InvocationEvent.dispatch(Unknown Source), java.awt.EventQueue.dispatchEvent(Unknown Source), java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source), java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source), java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source), java.awt.EventDispatchThread.pumpEvents(Unknown Source), java.awt.EventDispatchThread.pumpEvents(Unknown Source), java.awt.EventDispatchThread.run(Unknown Source)]

    Please answer me direct if you have anything to add or please let someone else answer that knows about it.WARNING:
    You'll not like my reply...
    ok now I change my stance and saying my question is not related to what I am trying to investigate on my app. If this is irony towards tjacobs' reply, be prepared for a culture schock around here.
    Lot of (most?) problems submitted here end up being solved very differently than what the questions started as. Often a poster will ask a narrow question, be asked about the context and reason for asking it, disclose what his real problem is, be warned that the problem may be orthogonal to his question, and be advised to attack and solve it in a very different way.
    Posters of questions solved this way are generally grateful, although sometimes they may be deterred by what they feel is a dismissing or blurring of their original question.
    The "which secret are you hiding" is a recurrent whinning too, and is, how to say it nicely,... utterly unprofesional and childish (at best).
    Keep in mind that all people here are volunteers, and bear on their time to help other people out. It is a nonsense to groan that someone offering you a hand is secretly plotting against you gaining knowledge. If he really was, he wouldn't answer you in the first place.
    Just a curious question as to why would there be 2 AWT-EventQueue threads. This can happen with applets is what I read. This swing app was simply lauched from a command prompt.Now I like it better.
    I can't answer your question, and my curiosity is piqued as well.
    Although it's a reasonable assumption that there is only one event queue per application context, and one thread serving it, the docs go a long way saying that it's implementation-dependant. I found this paragraph in the docs (+<JDK_HOME>/docs/api/java/awt/doc-files/AWTThreadIssues.html+):
    The reason is that AWT encapsulates asynchronous event dispatch machinery to process events AWT or Swing components can fire. The exact behavior of this machinery is implementation-dependent. In particular, it can start non-daemon helper threads for its internal purposes. In fact, these are the threads that prevent the example above from exiting. The only restrictions imposed on the behavior of this machinery are as follows:
    * EventQueue.isDispatchThread returns true if and only if the calling thread is the event dispatch thread started by the machinery;
    * AWTEvents which were actually enqueued to a particular EventQueue (note that events being posted to the EventQueue can be coalesced) are dispatched:
    o Sequentially.
    That is, it is not permitted that several events from this queue are dispatched simultaneously.
    o In the same order as they are enqueued.
    That is, if AWTEvent A is enqueued to the EventQueue before AWTEvent B then event B will not be dispatched before event A.
    * There is at least one alive non-daemon thread while there is at least one displayable AWT or Swing component within the application (see Component.isDisplayable).
    So, since we agree that it's implementation-dependant, could you add here your system's specs (OS, JRE version)?

  • Help!Can someone tell me the detail about Event Dispatch thread!

    I want to know the whole process about swing event,for example,the detail about
    event dispatch thread,the relation about event dispatch thread with event queue,and how the JVM painting the screen etc.
    Thanks!

    Read the tutorial titled "Creating a GUI Using JFC/Swing" found on this page":
    http://java.sun.com/docs/books/tutorial/
    Take a look at the table of contents, there is a section on threads which discusses the event thread and there are sections on painting. Actually take the time to read the whole tutorial.

  • How to synchronize two Event Dispatcher threads?

    I have two applications running in the same jvm. The flow should go like--
    a) First application (A1) has a swing window containing componets like buttons, text boxes etc.
    b) On click of this button, Event Dispatcher thread (T1) , calls the other application (A2).
    c) The second application A2, creates a swing window using EventQueue.invokeLater method and in the mean time Thread T1 should wait for this new A2 window to get some results from the database.
    Is it possible to stop thead T1 in between without freezing the GUI components of application A2.
    Thanks

    I think what tjacobs01 is getting at, is that there is only one Event Dispatcher Thread per JVM. So your question does not make sense. If there really is two EDT threads, then you are dealing with inter-process communication (since there would be two JVM processes, one for each application).
    It sounds like there is only one JVM, one EDT and two instances of a java.awt.Window. You probably think of the window == an application. In that case, you can probably solve your problem by executing the DB access (the long-running task) in the doInBackground() method of a SwingWorker.
    http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html

  • Future.get and the event despatch thread blocking

    neeeyaaarghhhh
    been tying myself in knots thinking about this
    Following one of the java tech tips I've been using Callable and Future objects when I want to return a result from a task, in my case it's usually some file processing
    So I have a file chooser gui, I select a file and launch my Callable and await the result in Future.get...
    Now the problem is... Future.get I understand blocks the calling thread until the computation / work in the Callable is done and the result returned. In this case the blocked thread will be the event despatch thread... which causes problems as during my file reading I have a JProgressBar running and updating. Well at least I did, now it doesn't show up at all as all the updates to the JProgressBar via invokeLater are queued (as event despatch thread is blocked) until after the work thread has finished
    How do I launch a Callable, await the result and have some limited gui activity as the task progresses? The only solution I've found is to have the ProgressBar in a modal dialog, to block out the rest of the gui like this whilst I do the work in the event despatch thread (and drop the idea of threading altogether)
    Is my mental modal of how worker threads should spin off from the event thread flawed or am I just missing some 1 line command?

    In the situation of updating the gui, you usually want to pass some sort of callback object to the asynchronous code and have that callback method run on the gui event thread.
    public class GuiClass {
    public void handleResult(Object data);
    public void startTask() {
      threadpool.execute(new Runnable() {
        public void run() {
          // ... do asynch work ...
          final Object myResult = ...;
          SwingUtilities.invokeLater(new Runnable() {
            public void run() {
              handleResult(myResult);
    }In this code, the startTask method is called on the gui thread. it starts some async work on the threadpool. when finished, the asynch task queues the result to be handled back on the gui thread. the handleResult method is called later on the gui thread with the final result. thus, no blocking of the gui thread.
    The Callable interface is great for when the invoking thread needs to wait for a result, but you pretty much never want to do this with the gui thread.

  • WHY more Event-Dispatching threads in Applet ?

    When an applet is running, I find there are more than one Event-Dispatching Thread (EDT). I observed this through the Java Plug-in debug option -- attaching jdb.
    Swing Applications requires, access to any GUI object strictly on an Event-Dispatching Thread. Taking Event-Dispatching Thread to be a single thread, lots of synchronization consideration have been overlooked. When executing as an application, there is only one EDT; however when executing an an Applet there is more than one EDTs, but belonging to different thread groups. (like main, applet etc).
    WHY is this ?
    From a GUI developer's perspective is it safe to assume EDT is single threaded and NO sychronization issues needs to be taken care, which otherwise will be required ?
    Please let me know if you would require any more information to answer this query.
    Thanks a lot, in advance, for your time and effort. :-)
    -Soms.

    MORE supporting information:
    The jdb Thread information: (Note that there are 2 EDTs - Main and applet thread groups). I need to know WHY 2 EDTs ?
    threadsGroup system:
    (java.lang.ref.Reference$ReferenceHandler)0x9c0 Reference Handler cond. waiting
    (java.lang.ref.Finalizer$FinalizerThread)0x9c1 Finalizer cond. waiting
    (java.lang.Thread)0x9c2 Signal Dispatcher running
    (java.lang.Thread)0x9c3 Thread-1 unknown
    (sun.plugin.cache.CleanupThread)0x9c4 Cache Cleanup Thread cond. waiting
    Group main:
    (java.lang.Thread)0x9c6 main running
    (java.util.logging.LogManager$Cleaner)0x9c7 Thread-0 unknown
    (java.lang.Thread)0x9c8 AWT-Shutdown cond. waiting
    (java.lang.Thread)0x9c9 AWT-Windows running
    (java.lang.Thread)0x9ca Java2D Disposer cond. waiting
    (java.awt.EventDispatchThread)0x9cb AWT-EventQueue-0 waiting in a monitor
    Group Plugin Thread Group:
    (java.lang.Thread)0x9ce Main Console Writer cond. waiting
    Group http://rndpc192/periview/-threadGroup :
    (java.lang.Thread)0x9cf thread applet-com.peri.rnd.monitor.alaska.AlaskaApplet.class cond. waiting
    (java.lang.Thread)0x9d0 TimerQueue cond. waiting
    (java.awt.EventDispatchThread)0x9d1 AWT-EventQueue-2 waiting in a monitor
    (java.lang.Thread)0x9d2 Thread-4 waiting in a monitor
    (java.lang.Thread)0x9d3 Thread-5 unknown
    (java.lang.Thread)0x9d4 Thread-8 unknown
    (java.util.TimerThread)0x9d5 Thread-9 cond. waiting
    (java.lang.Thread)0x9d6 Thread-10 running
    (java.lang.Thread)0x9d7 Thread-12 unknown
    (java.util.TimerThread)0x9d8 Thread-13 waiting in a monitor
    (java.lang.Thread)0x9d9 Thread-14 waiting in a monitor
    (java.lang.Thread)0x9da Thread-15 cond. waiting

  • In swing for painting is separte thread from event-dispatching thread

    hi,
    event -dispatching thread is diffenent from paint thread in swing ???

    I don't believe so... or if it is, they have a special relationship tieing them together.
    why?

  • Can I modify a table model outside of the event thread if it's not seen?

    I have a JTable that I use to display several table models (I'm extending DefaultTableModel); I switch between the models using JTable.setModel.
    If model A is active and currently being viewed, I of course make sure any updates are done using SwingUtilities.invokeLater().
    My question is: Can I modify an "inactive" table, say table B, without using invokeLater(), for example B.setValueAt() etc.

    Isn't a model connected to an instance by JTable.setModel()? (Or by passing the model as a parameter in new JTable()) Yea. I meant connected to a JTable's UI. Or more specifically, listeners are installed on the model.
    if data is changing and the user is not currently viewing that data, I want to change the table model in another threadI would argue that this is thread safe:
    1) When a table becomes 'inactive' (not showing in any way) then you set the model to some static empty one.
    table.setModel(EMPTY_MODEL);This should happen on the EventDispatchThread. Setting the model to the empty one will uninstall all the listeners on the actual model.
    2) Freely modify the table's actual model in another Thread.
    3) When the table is about to become 'active', then you set the model back to the original one.
    table.setModel(originalModel);This should happen on the EventDispatchThread. In particular, the other thread should execute it with an invoke later. That way, proper synchronization occurs and the EDT sees all the changes made to the original model.

  • How to execute code when press the ENTER key

    Hello,
    I've write the code in Key-ENTER trigger, but it doesn't work when I press ENTER key.
    Best Regards
    Joe

    Matth M
    Thank you.
    The following msg. from help system shows that key-enter trigger will execute when the ENTER pressing event occurs. Need your more help.
    Regards
    Joe
    >
    (index: "DO_KEY" )
    Executes the key trigger that corresponds to the specified built-in subprogram. If no such key trigger exists, then the specified subprogram executes. This behavior is analogous to pressing the corresponding function key.
    Built-in............Key Trigger............Associated Function Key
    ENTER............Key-ENTER............[Enter]

  • Flags and the Event Thread

    I was writing code for a game and I realized that the AWT event thread could change the value of a flag while I'm in the process of updating the game state. This can cause a few problems, or it could even leave events not handled because of it. I see code like this all the time as a fix to the threading issues, am I missing something or is it really a solution? I can't post the actual code as it's too long, so I created a simple example:
    import java.awt.event.*;
    import javax.swing.*;
    public class EventTest extends JFrame implements KeyListener, Runnable
         private boolean isKeyDown;
         public EventTest()
              setSize(500, 500);
              setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              setVisible(true);
              addKeyListener(this);
              new Thread(this).start();
         public void keyPressed(KeyEvent event)
              //synchronized(this)
                   isKeyDown = true;
         public void keyReleased(KeyEvent event)
              //synchronized(this)
                   isKeyDown = false;
         public void keyTyped(KeyEvent event) {}
         public void run()
              // game loop
              while(true)
                   //synchronized(this)
                        boolean cache = isKeyDown;
                        System.out.print(isKeyDown); // before
                        System.out.print(' ');
                        /* event handling, game logic, etc. done here
                           do some useless operation to simulate this */
                        long time = System.currentTimeMillis();
                        while(time + 1 > System.currentTimeMillis());
                        System.out.println(isKeyDown); // after
                        if(cache != isKeyDown)
                             System.out.println("PROBLEM!");
                        // render everything to the screen
                   try
                        Thread.sleep(100);
                   } catch(InterruptedException e) {}
         public static void main(String[] args)
              new EventTest();
    }Basically I have a game loop, where I update the game state, handle events, then draw things to the screen. Each time a key is pressed or released, I set the appropriate value to isKeyDown from the AWT event thread. The desirable output is to have the booleans equal to each other so that "false false" or "true true" is printed out on the screen constantly, but once in a while I'll get a "false true" or "true false", which is expected but obviously not wanted.
    So one solution is right there commented out (synchronizing), though most people seem to avoid it. I see everybody using flags like this, so I'm wondering if I'm missing some obvious solution to the problem or if it's really even that big of a deal. I don't see any other fix, but that's why you're all here. ;)
    Thanks.

    Swing related questions should be posted in the Swing forum.
    I converted your simple example to use a Swing Timer instead of a while(true) loop with a Thread.sleep. I experienced no problems as expected since all the code will be executed in the Event Dispatch Thread (EDT).
    Of course using this approach could make the game less responsive if your game logic is extensive and hogs the EDT, but given that you try to invoke your game logic every 100 millisecond I assume it can't be that extensive.
    Anyway here is the code I used as a test:
    import java.awt.event.*;
    import javax.swing.*;
    public class EventTest extends JFrame implements KeyListener, ActionListener
         private boolean isKeyDown;
         public EventTest()
              setSize(500, 500);
              setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              setVisible(true);
              addKeyListener(this);
              new Timer(100, this).start();
         public void keyPressed(KeyEvent event)
              isKeyDown = true;
         public void keyReleased(KeyEvent event)
              isKeyDown = false;
         public void keyTyped(KeyEvent event) {}
         public void actionPerformed(ActionEvent e)
              boolean cache = isKeyDown;
              System.out.print(isKeyDown); // before
              System.out.print(' ');
              /* event handling, game logic, etc. done here
                 do some useless operation to simulate this */
              long time = System.currentTimeMillis();
              while(time + 1 > System.currentTimeMillis());
              System.out.println(isKeyDown); // after
              if(cache != isKeyDown)
                   System.out.println("PROBLEM!");
         public static void main(String[] args)
              new EventTest();
    }

Maybe you are looking for