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();
}

Similar Messages

  • 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.

  • How can I archive photos in iPhoto to a hard drive and retain the Album folders and the Events?

    How can I archive photos in iPhoto to a hard drive and retain the Album folders and the Events?  I tried to Export the Albums but just transferred the files individually.

    If you want to maintain the iPhoto organisation then back up the iPhoto Library.
    If you want to export to the Finder, well you need to create a folder for the contents of an Album and expot to that.
    If you have an older version of iPhoto: Apps like iPhoto2Disk or PhotoShare will help you export to a Folder tree matching your Events. This feature is built in to iPhoto 11.
    This User Tip
    https://discussions.apple.com/docs/DOC-4921
    has details of the options in the Export dialogue.

  • Why don't my photos appear as they do in iPhoto on my Apple Computer. Even though I specify to sync all Events, Faces, etc. the iPad 2 is missing Faces categories and the Events are in a different order.

    Why don't my photos appear as they do in iPhoto on my Apple Computer. Even though I specify to sync all Events, Faces, etc. the iPad 2 is missing Faces categories and the Events are in a different order.

    1) The best way to relocate the iTunes library folder is to move the entire iTunes folder with all subfolders to the new path, then press and hold down shift as start iTunes and keep holding until prompted to choose a library, then browse to the relocated folder and open the file iTunes Library.itl inside it.
    If you've done something different then provide some more details about what is where and I should be able to help.
    2) Purchases on the device should automatically transfer to a Purchased on <DeviceName> playlist, but it my depend a bit on whether automatic iCloud downloads are enabled. If there is a cloudy link then the transfer might not happen. You can use File > Devices > Transfer Purchases. In iTunes you should also check out iTunes Store > Quick Links > Purchased > Music > Not on this computer.
    3) Backup the device, then immediately restore it. In some cases you need to add a restore as new device into that equation. Obbviously not to be attempted until you're sure all your media is in your library. See Recover your iTunes library from your iPod or iOS device should it be needed.
    4) I believe there is complimentary 1 incident 90-day support with hardware purchases, but no free software support for iTunes itself. AppleCare gets you a different level of support.
    tt2

  • Flag and new event

    Can multiple photos be flagged from different events and saved to a new event at the same time keeping the flagged photos in their original events?

    No
    a specific photo can only exist in one event
    If you duplicated the photos in the source event then flagged the new one (actually either one) you could do taht - you would, of course double the storage used for those photos winch there are now two of each - and any edits, =delete, etc would only operate on the one you did it to leaving the other copy alone (maybe what you intend?)
    LN

  • I get the following error and the old thread on this did not solve my problem. Does anyone have an idea how to fix it. The error is "an error occured sending command to application"

    When I open a link from Microsoft outlook I get the following error
    "An error occured sending command to application" The old thread on this does not help and it is closed.
    == This happened ==
    Every time Firefox opened

    Hello Anonymous.
    You will need to contact Microsoft for support on Outlook.

  • How do i remove type form a flag and the flag return to original?

    help on removing a text from a flag and flag returning to original?

    Gary,
    IT sounds as if you have a number of rectangles/squares forming the checkered pattern of the flag.
    If the pattern is repetitive, you may be able to Alt/OptionClick some of those round the gap and move copies to fill it; rectangles/squares with cutouts would have to be deleted.
    A screenshot may give rise to better suggestions.
    It is an hour and a half past midnight over here, so I shall have to attend to other duties, before the sun is up.

  • 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.

  • Error display the date in the calendar and the event is lost in the list of the day

    At one point written on November 2, in another November 3 in the list for the day and 2 and 3 of this event no!

    Hi,
    Try this code.
    TYPES: BEGIN OF type_t_date,
    mm(2) TYPE c,
    filler1(1) TYPE c,
    dd(2) TYPE c,
    filler2(1) TYPE c,
    yyyy(4) TYPE c,
    END OF type_t_date.
    DATA: t_ddate TYPE type_t_date.
    CONSTANTS: c_fil TYPE c VALUE '.'.
    t_ddate-mm = rs_sdate-mm.
    t_ddate-dd = rs_sdate-dd.
    t_ddate-yyyy = rs_sdate-yyyy.
    t_ddate-filler1 = c_fil.
    t_ddate-filler2 = c_fil.
    CONCATENATE t_ddate-mm t_ddate-filler1 t_ddate-dd t_ddate-filler2 t_ddate-yyyy INTO rv_ddate.
    Regards,
    Amit

  • I have uploaded photos to iPhoto but on completion my Mac crashed and the events are present but no photos remain. My iPhoto is managed version 11 9.4.3 (720.91)

    Is there anythinh I can do to retrieve the pics? I uploaded from 2 SDHC cards, one of 230 pic (which I deleted from the card) and another of 1,200+ pic, which I did not delete.

    a best practice to is to never have any computer program (including iPhoto) delete the photos from the card but to import the photos and keep them and then after at least one successful backup cycle has completed and then reformat the card --  I use three very large (32 GB) cards in rotation so I do not reformat for typically a year or more giving me one more long term backup of my photos
    Try Back up your iPhoto library, Depress and hold the option (alt) and command keys and launch iPhoto - rebuild your iPhoto library database
    LN

  • 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.

  • I copied my iPhoto library to an external hard drive and all the event windows are black. Once you click on a square the photos are still there. How do I fix that?

    I copied my iPhoto library to an external hard drive and the event windows show up black.
    The photos are still there once I click on an event but they don't show in the window.
    My next step is to delete the iPhoto library from the internal memory to free some memmory space but I don't want to do this until I see that the library works fine on the external hard drive.
    How do I fix that?

    Hold down the "option" + "command" keys and launch iPhoto.
    Select the "Rebuild Thumbnails" choice.

  • I have a doubt about The Single-Thread Rule

    The [url http://java.sun.com/docs/books/tutorial/uiswing/overview/threads.html#rule]Single Thread Rule states:
    Rule: Once a Swing component has been realized, all code that might affect or depend on the state of that component should be executed in the event-dispatching thread.
    I began to wonder about this because so much code seems to work just fine when it isn't executed in the event dispatching thread. Why are there exceptions? I went looking for some code which acted differently when executed on the event thread than when it was not. I found this
    http://forum.java.sun.com/thread.jsp?forum=57&thread=410423&message=1803725#1803725
    Now I started wondering why this was the case. What I found was that DefaultCaret adds a document listener to the document of the JTextComponent. In this listener, the insertUpdate() method specifically tests if it is running on the event dispatch thread and if it is, it updates the caret position.public void insertUpdate(DocumentEvent e) {
        if (async || SwingUtilities.isEventDispatchThread()) {
            // ... update the caret position ...
    }I then copied the code from DefaultCaret and made a MyCaret. I needed to tweek the code a little bit, but it ran. I removed the event thread test. It worked outside the event thread. There was a small difference in the results though. The textarea did not scroll all the way to the bottom. Almost, but not quite. I didn't test enough to make sure this was the only problem, but there was at least one problem.
    Now I started think about why this would be. The thought crossed my mind that the order of the events which were posted to the event queue were probably important. Sun found bugs when components were updated out of the event thread, so they essentially ignored events which weren't on the event thread and created the The Single-Thread Rule.
    A few days pass. I'm starting to wonder if Sun could have done a better job making Swing components thread safe. I also don't know that this specific case I found was the rule or the exception to the rule. But without insight into the design philosopy of Swing, I would have to examine all their components and see how they have written them and see if I can come up with a better design. That sound like a lot of work. Especially without getting paid for it.
    But wait a second, all you have to do is call the append() method of JTextArea on the event thread. If that is the case, why didn't they write the freakin component that way? Well, I'll try itclass MyTextArea extends JTextArea {
      public MyTextArea(int rows, int columns) { super(rows,columns); }
      public void append(final String text) {
        if (SwingUtilities.isEventDispatchThread()) super.append(text);
        else {
          SwingUtilities.invokeLater(new Runnable() {
            public void run() { myAppend(text); }
      private void myAppend(String text) { super.append(text); }
    }I change [url http://forum.java.sun.com/thread.jsp?forum=57&thread=410423&message=1803725#1803725]camickr's code to use a MyTextArea and it works fine without calling from the event thread. I've essentially moved The Single-Thread Rule to the component itself rather than relying on each and every one of the [url http://www.aboutlegacycoding.com/default.htm?AURL=%2FSurveys%2FSurvey6intro%2Easp]2.5 million Java programmers worldwide to use SwingUtilities.invaokeLater().
    Now for my question...
    Why didn't Sun do this?

    Swing is slow enough as it is. Lets not make it slower
    just
    because dense "programmers" don't know what they are
    doing.I agree with you in defending the current model, but aren't you a bit harsh there?!? ;-)
    Well, there are a number of not-so-dense programmers that expect such high-level components to be thread-safe. The question is worth asking whether Sun intentionally favor the explicit thread management for performance reasons, or whether this was an oversight.
    I'd go for the former (intentional) : indeed any GUI toolkit is inherently thread-based; there is always a distinction between the graphical thread(s) and the application threads - and the programmer always has to manage explicit thread creation to handle long-running event handlers without blocking the event dispatching thread. Extending thread concerns to the updating of components is therefore not a big move.
    So it seems fair that a core GUI toolkit does not hide thread issues (though to the best of my knowledge there is no such limitation in updating AWT components), or at least that's what Sun deemed.
    An ease-of-use-focused toolkit wrapping the core toolkit for thread-safety can be provided as a third-party product. Though I agree that wrapping the dozens of existing widgets and hundreds of methods is cumbersome - and the lack of such products probably shows it would have a low added value to trained developpers.
    Because your way is an extra method call and if
    statement, neither of which is necessary if you already know you
    are in the correct thread. Now count the number of methods
    which will need to be changed (and add up the extra cost).Indeed it's quite common to update several properties of several widgets in one bulk (when user clicks "OK", add a row to the table, change the title of the window, update status bar, re-enable all buttons, change some color,...).
    In this case explicit thread management doesn't spare one if but a dozen of redundant ifs!
    Note that there could have been if-less ways to cope for thread safety, such as creating a copy of the component's model when a change is made to a component, and switching the model only before paint() is called in the event-dispatching - of course coalescing all changes into the same "updated" model until paint() is called.
    But this would trade ease of use for redundant memory consumption, especially for some components with potentially huge models (JTree, JTable, JTextArea,...). And Swing appears to be already quite memory-greedy!

  • JColorChooser hangs event thread on Linux x64

    I am finding that repeatedly displaying a JColorChooser, picking a color, and clicking "OK" will hang the event thread in 64-bit Ubuntu 9.04 (Java 6 Update 13). Usually it takes between 2 to 20 launches of the JColorChooser before the color chooser will not launch and the UI is frozen. I cannot reproduce this using 32-bit Windows XP. I can even use the Sun Java Tutorial code and the problem occurs every time (Tutorial Link for a Color Editor in a JTable: http://java.sun.com/docs/books/tutorial/uiswing/examples/components/TableDialogEditDemoProject/src/components/ColorEditor.java).
    Has anyone else seen this problem and found a workaround of any kind? Or has anyone tested this on 64-bit linux with Java 6 without problems? Thanks much to all for any help.

    Here is a testbed that will produce the problem for me.
    * 1) Run the testbed.
    * 2) Click the button.
    * 3) Pick a new color swatch.
    * 4) Click OK.
    * 5) Repeat steps 2-4 until the color chooser does not launch.
    * (This was between 1 and 25 times for me)
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JColorChooser;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    * This class demonstrates a problem with JColorChooser.
    * I encountered this problem launching a color chooser from a
    * table cell, thus this example is based on table cell editor
    * code from the Java Tutorial (ColorEditor.java). I have added a
    * main() and removed some of the Table related noise.
    * 1) Run.
    * 2) Click the button.
    * 3) Pick a new color swatch.
    * 4) Click OK.
    * 5) Repeat steps 2-4 until the color chooser does not launch.
    * (This was between 1 and 25 times for me)
    public final class ColorChooserTest implements ActionListener
    private Color currentColor = Color.BLUE;
    private final JButton button = new JButton("Push Me");
    private final JColorChooser colorChooser;
    private final JDialog dialog;
    private static final String EDIT = "edit";
    private final JFrame frame = new JFrame("JColorChooser TestBed");
    public ColorChooserTest() {
    button.setActionCommand(EDIT);
    button.addActionListener(this);
    button.setBorderPainted(false);
    button.setBackground(currentColor);
    //Set up the dialog that the button brings up.
    colorChooser = new JColorChooser();
    dialog = JColorChooser.createDialog(button,
    "Pick a Color",
    true, //modal
    colorChooser,
    this, //OK button handler
    null); //no CANCEL button handler
    final JPanel holder = new JPanel(new BorderLayout());
    holder.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
    holder.add(button, BorderLayout.CENTER);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(holder, BorderLayout.CENTER);
    frame.pack();
    public void actionPerformed(final ActionEvent e)
    if (EDIT.equals(e.getActionCommand()))
    //The user has clicked the cell, so
    //bring up the dialog.
    button.setBackground(currentColor);
    colorChooser.setColor(currentColor);
    dialog.setVisible(true);
    else
    //User pressed dialog's "OK" button.
    currentColor = colorChooser.getColor();
    button.setBackground(currentColor);
    public static void main(final String[] args)
    final ColorChooserTest x = new ColorChooserTest();
    x.frame.setSize(300, 300);
    x.frame.setVisible(true);
    }

  • Swing event queue, modal dialogs, event threads, etc...

    Hey all,
    So I am playing around with the focus manager, swing event thread and event queue, etc. Learned quite a bit. I am also playing around with test automation of our UI, using jfcUnit. I have written a few simple apps to play aorund with record/playback, coding tests, etc. What this thread is about though, is figuring out how modal and non-modal dialogs "take over" the event thread/queue? The reason I ask is, if I put a simple test harness like tool embeded in my app as a separate pop-up modal dialog, and from within it there is a GUI that I can use to select a "Test" to run. Now, when I run this test, jfcUnit needs to run on the main window, not within my non-modal dialog. What I am not sure of, however, is that if by using a non-modal dialog all events will go to the main event thread? I mean, I know if I mouse over my second non-modal frame (spawned from the application frame), that events will trigger for that dialog. I remember reading somewhere that modal dialogs "block" the main event queue, all left over events are given to the newly added event queue (presumably by the modal dialog) and existing left-over events get moved to the event queue. If that is the case, I am curious why events for the "old" queue are moved to the new queue if they were orginally intended for the old queue? I would think a "flush" before adding a new queue would be more appropriate so that the old queue can process all of its intended events.
    Now, I am just about to try this, but I am hoping a non-modal pop-up will not interfere with the jfcUnit running the UI of the main window. I am guessing, however, that it might. How are non-modal dialogs handled in terms of events and the event queue? Is it the same as modal dialogs? Or is there no blockage of the mainwindow event queue? If there is no blockage, than any sort of automation based on relative positions to a window may occur on the non-modal dialog, in which case it's best to hide the non-modal dialog during running of these tests.
    What are your thoughts, or better yet, knowledge of this topic? A decent explanation from a developer standpoint and not from the API's which dont give some of the more detailed info I am seeking is what I am hoping to get out of this.
    Thanks.

    Check this out. First, AWTListener has a LOT of
    different types you can register it for. I ORd all
    them together and when I ran my app, it took almost 30
    minutes for it to show up because of the huge stream
    of events being spit out via System.out. ...Yes, that doesn't surprise me in the least. There's hundreds of events that are fired around, usually unbeknownst to the user for every little thing. Lots of component and container events, in particular.
    Just make sure you OR ( using | not || ) ALL the
    "mask" values you want to watch for. That may be why
    you aren't seeing anything. When I did all that, and
    opened a menu, a ton of events came out.Maybe, I'll try that again, but I did specifically add an ActionEvent mask to get action events, and that should be all I need to get action events on buttons or menu items, and it wasn't getting them for either. It was only getting events on buttons when I used SwingEventMonitor, but not menu items.
    So I don't quite understand enough of the underlying event handling. Although, I suspect it could have something to do with the fact that these are Swing components, not AWT components (which their native peers) and it's pretty clear from AbstractButton (or was it DefaultButtonModel) how ActionEvents are fired, and they don't seem to have any connection to the code that deals with AWTListeners.
    My problem is that I kinda need a way to catch events without having a listener attached directly. Normally, I would have a listener, but there's this situation whereby an action may be triggered before I can get hold of the component to attach my listener to it. Perhaps I can get mouse press/release and just deal with it that way.
    Let me know if you did that and still didn't see what
    you were looking for. After playing with this, I am
    guessing the main reason for AWTListener is to
    register a listener for a specific type of event,
    instead of listening to them all, hence avoiding lots
    of extra overhead. Then again, the main event
    dispatcher must do a decent amount of work to fire off
    events to listeners of specific awt event types.Yes, it's definitely that. There's no point in sending events if no one is listening for it, so it does save some time.
    You are right, popup menus I think are dialogs, I
    don't know for sure, but you can access them via the
    JMenu.getPopupMenu() and JMenu.isPopupShowin().
    However, I am still not getting my test stuff working
    quite right.
    Yes, for menu popups. For a JPopupMenu on a right-click on any component (tree or whatever), I had a need to know about that from any arbitrary application (it's this GU testing app I'm working on), and since the popup menu doesn't belong to any component before it's shown, I couldn't necessarily know about it til it was displayed. I managed to use a combination of HierarchyEvents (using an AWTEventListener) and "component added" ContainerEvents. Not a simple matter, but it seems to work well.

Maybe you are looking for

  • How do I create a dvd backup of library in the very latest iTunes,with windows xp?

    How do I create a dvd backup of library with itunes version 11.1.4.62? Using windows xp.

  • REP-9: A fatal error occured: in the toolkit.

    Ok, so I just installed a fresh install of Forms and Reports 11.1.2.0.0 and applied the most recent patch for it like I've been doing to the other servers in my environments. This one is the only one that gives me errors when I try to run a report. H

  • How to find variant config material changes

    Hi! I have a requirement to compare variant config material under an equipment sales order. Scenario is:- Suppose company has sold one product and that product is variant configured. Under configuration tab user has selected different characteristics

  • SQL Data Modeler 3.0 EA1 (Data Modeler 3.0 EA1.)

    On the newest release of Data Modeler (3.0.0 Build 649), if I have a relational table with an object type structure, I still cannot pick one of the attributes in the structure to be part of a the primary key for the relational table. Oracle 11gR2 doe

  • Any function module available for...

    hi all, i need a function module to do a goods receipt for the PO using movement type 161, movement ind B, goodsmvt code '01'. i couldnt able to post using BAPI_GOODSMVT_CREATE as iam getting 'NO GOODS RECEIPT POSSIBLE FOR PO XXXXXXXX XXXXX'. So is t