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.

Similar Messages

  • Modal dialog does not close until function finish

    Hello
    I am a modal dialog (yes/no buttons). When user selects YES, a function is executed. My problem is: Dialogo does not close until function finish.
    Many thanks for your help.
    This is the call to show modal dialog:
    boolean myRes;
    dlgYesNo.setTitle(" SINCRONIZE");
    dlgYesNo.setPreguntaUp("�Do you want to sincronize?");
    dlgYesNo.show();
    myRes = dlgYesNo.respDialogo();
    if (!myRes) return; // User selects NO
    sincronizeData(); //MODAL DIALOG DOES NOT CLOSE UNTIL THIS FUNCTION FINISH!!!
    This is the class to create modal dialog:
    public class DialogoYesNo extends java.awt.Dialog {
    /** Creates new form DialogoYesNo */
    public DialogoYesNo(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();
    this.setSize(200,125);
    this.setResizable(false);
    Dimension d = this.getToolkit().getScreenSize();
    this.setLocation((d.width-getSize().width)/2, (d.height-getSize().height)/2);
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    private void initComponents() {
    btYes = new java.awt.Button();
    lblDialogCentro = new java.awt.Label();
    lblDialogUp = new java.awt.Label();
    btNo = new java.awt.Button();
    lblDialogDown = new java.awt.Label();
    setLayout(null);
    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent evt) {
    closeDialog(evt);
    btYes.setLabel("Si");
    btYes.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    btYesActionPerformed(evt);
    add(btYes);
    btYes.setBounds(30, 80, 60, 24);
    lblDialogCentro.setAlignment(java.awt.Label.CENTER);
    lblDialogCentro.setText("a");
    add(lblDialogCentro);
    lblDialogCentro.setBounds(10, 40, 180, 20);
    lblDialogUp.setAlignment(java.awt.Label.CENTER);
    add(lblDialogUp);
    lblDialogUp.setBounds(10, 30, 180, 20);
    btNo.setLabel("No");
    btNo.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    btNoActionPerformed(evt);
    add(btNo);
    btNo.setBounds(110, 80, 60, 24);
    lblDialogDown.setAlignment(java.awt.Label.CENTER);
    add(lblDialogDown);
    lblDialogDown.setBounds(10, 50, 180, 20);
    pack();
    private void btYesActionPerformed(java.awt.event.ActionEvent evt) {
    // Add your handling code here:
    respuesta = true;
    setVisible(false);
    dispose();
    private void btNoActionPerformed(java.awt.event.ActionEvent evt) {
    // Add your handling code here:
    respuesta = false;
    setVisible(false);
    dispose();
    /** Closes the dialog */
    private void closeDialog(java.awt.event.WindowEvent evt) {
    // Add your handling code here:
    * @param args the command line arguments
    public static void main(String args[]) {
    new DialogoYesNo(new java.awt.Frame(), true).show();
    public void setPreguntaUp(String p){       
    lblDialogUp.setVisible(true);
    lblDialogDown.setVisible(true);
    lblDialogCentro.setVisible(false);
    lblDialogUp.setText(p);
    public void setPreguntaDown(String p){
    lblDialogUp.setVisible(true);
    lblDialogDown.setVisible(true);
    lblDialogCentro.setVisible(false);
    lblDialogDown.setText(p);
    public void setPreguntaCentro(String p){
    lblDialogUp.setVisible(false);
    lblDialogDown.setVisible(false);
    lblDialogCentro.setVisible(true);
    lblDialogCentro.setText(p);
    public void centrarPantalla(){
    Dimension d = this.getToolkit().getScreenSize();
    this.setLocation((d.width-getSize().width)/2, (d.height-getSize().height)/2);
    public boolean respDialogo(){
    return respuesta;
    // Variables declaration - do not modify
    private java.awt.Button btNo;
    private java.awt.Label lblDialogCentro;
    private java.awt.Button btYes;
    private java.awt.Label lblDialogUp;
    private java.awt.Label lblDialogDown;
    // End of variables declaration
    private boolean respuesta = false;
    }

    Hello
    This case works fine using following line to execute code after modal dialog:
    new Thread(new Runnable(){ public void run() { netCodeFunction(); }}).start();
    Regards

  • How to make a dalog process custom events when blocked by modal dialog

    Hi,
    I would like to understand the way modal dialogs block other dialogs so that I can properly solve an issue I'm having with two modal dialogs, one blocking the other.
    I have an application, netbeans platform based, that opens a JDialog, NewDiskDlg, with it's modal property set to true. This dialog is responsible for starting a thread that will process a given number of files, from time to time, depending on some conditions, this thread will send events to the NewDiskDlg.
    When this thread is started, the NewDiskDlg creates a new JDialog, also with the modal property set to true. Both dialogs have the same parent, the main window. And this works as I expected, the second dialog, ActiveScanningDlg, opens on top of the NewDiskDlg and, until the thread stops, the dialog stays visible.
    When the thread stops an event is sent to this two dialogs signaling that the job has been completed, and here is my problem. The second dialog, the one that is visible when the event arrives, receives the event and executes the dispose() method, releasing control to the NewDiskDlg in the back, but the NewDiskDlg does not receive the event and does not process it correctly.
    I understand the no input can be sent to a blocked window, but does that include calling upon the window's methods?
    I've been looking for some help on this but my search terms are not good enough to provide me with any useful information. I've also read the topic on the focus system that is present in the Java Tutorial but I feel that that is not what I should be looking at.
    The following code is a snippet of the important parts that I described:
    NewDiskDlg has the following methods to process the events
        public void readingStarted(ReadingEvent evt) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    scanningDlg.showCentered();
        public void readingFile(ReadingEvent evt) {
            //DO NOTHING
        public void readingStopped(ReadingEvent evt) {
            Lookup.getDefault().lookup(MediaReader.class).removeListener(this);
            if (!showAgain) {
                dispose();
        public void readingAborted(ReadingEvent evt) {
            JOptionPane.showMessageDialog(this, "", "", JOptionPane.ERROR_MESSAGE);//TODO: i18n on the error messagens
            Lookup.getDefault().lookup(MediaReader.class).removeListener(this);
        }ActiveScanningDlg processes the events like this:
        public void readingStarted(ReadingEvent evt) {
            //DO NOTHING
        public void readingFile(ReadingEvent evt) {
            jpbReadingProgress.setString(evt.getCurrentFileName());
        public void readingStopped(ReadingEvent evt) {
            Lookup.getDefault().lookup(MediaReader.class).removeListener(this);
            dispose();
        public void readingAborted(ReadingEvent evt) {
            readingStopped(evt);
        }This is an example on how the events are sent:
        private void fireReadingFile(ReadingEvent evt) {
            for (ReadingListener l : listeners) {
                l.readingFile(evt);
        }

    Hi,
    You have to check the Tolerance limits set for the following tolerance keys. In case if any where the limit is breached the systems blocks the Invoice as 'R - Invoice verification'. Please check the limits set for all these keys.
    AP - item amount variance (if you have activated the item check)
    DQ and DW - for Quantity variance
    PP - price variance with the order price
    ST - date variance
    VP - Moving average price variance
    Regards,
    Kathir

  • Trying to make up a Modal Dialog with customized event dispatcher

    Hello everyone.
    I try to make up a ModalDialog class with customized event dispatcher in order to wait an invoker.
    But it fails :-(
    import javafx.event.ActionEvent;
    import javafx.event.Event;
    import javafx.event.EventDispatchChain;
    import javafx.event.EventHandler;
    import javafx.event.EventTarget;
    import javafx.event.EventType;
    import javafx.scene.Group;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.layout.BorderPane;
    import javafx.scene.layout.HBox;
    import javafx.stage.Modality;
    import javafx.stage.Stage;
    import javafx.stage.StageStyle;
    import javafx.stage.Window;
    import javafx.stage.WindowEvent;
    import com.sun.javafx.stage.WindowEventDispatcher;
    import java.util.ArrayList;
    public class ModalDialog extends Stage {
      ArrayList<Button> buttons;
      int rc;
      Stage stage;
      Event event;
      EventDispatchChain tail;
      public ModalDialog( Window owner, String title ){
        initModality( Modality.APPLICATION_MODAL );
        initOwner( owner );
        initStyle( StageStyle.UTILITY );
        setTitle( title );
        stage = this;
      public void setContents( Group group, ArrayList<Button> buttons ){
        BorderPane root = new BorderPane();
        Scene scene = new Scene(root);
        setScene(scene);
        root.setCenter( group );
        this.buttons = buttons;
        HBox buttonPane = new HBox();
        buttonPane.setSpacing(10);
        for( int i=0 ; i<buttons.size() ; i++ ){
          buttons.get(i).setOnAction( actionHandler );
        buttonPane.getChildren().setAll( buttons );
        root.setBottom( buttonPane );
      public int show( double screenX, double screenY ){
        setX( screenX ); setY( screenY );
        show();
        MyWindowEventDispatcher dispatcher =  new MyWindowEventDispatcher( stage );
        setEventDispatcher( dispatcher );
        while(true){
          event = dispatcher.dispatchEvent( event, tail );
          EventType<? extends Event> type = event.getEventType();
          if( type==WindowEvent.WINDOW_HIDDEN ){
            break;
        return( rc );
      EventHandler<ActionEvent> actionHandler = new EventHandler<ActionEvent>() {
        public void handle( ActionEvent e ){
          EventTarget src = e.getTarget();
          rc = buttons.indexOf( src );
          stage.hide();
      class MyWindowEventDispatcher extends WindowEventDispatcher {
        public MyWindowEventDispatcher( Window window ){
          super( window );
        public Event dispatchEvent( Event event, EventDispatchChain tail) {
          ModalDialog.this.event = dispatchCapturingEvent( event );
          ModalDialog.this.tail = tail;
          return( event );
    }A sample code to invoke ModalDialog
    import java.util.ArrayList;
    import javax.swing.JOptionPane;
    import javafx.application.Application;
    import javafx.event.EventHandler;
    import javafx.scene.Group;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.Label;
    import javafx.stage.Stage;
    import javafx.stage.WindowEvent;
    public class WindowEvent06 extends Application {
      Stage mainStage;
      public void start(Stage stage) throws Exception {
        Group root = new Group();
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.setTitle("WindowEvent06");
        mainStage = stage;
        stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
          public void handle(WindowEvent e){
            ModalDialog dialog = new ModalDialog( mainStage, "Question" );
            Button yes = new Button( "Yes" );
            Button no  = new Button( "No" );
            ArrayList<Button> buttons = new ArrayList<>();
            buttons.add(yes); buttons.add(no);
            Label msg = new Label( "Really Exit ?" );
            Group groupInDialog = new Group();
            groupInDialog.getChildren().add( msg );
            dialog.setContents( groupInDialog, buttons );
            int ans = dialog.show( 300, 300 );
            System.out.println("returned from a modal dialog");
            if( ans == 1 ){
              e.consume(); // this blocks window closing
        stage.show();
      public static void main(String[] args) {
        launch(args);
    }

    Hi,
    The logic what you follows is some what in the right direction but need to have some changes.
    What I would say is, first consume the windowClose event. Then open the dialog box and close the parent accordingly.
    So after refactoring your code.
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.scene.Group;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.Label;
    import javafx.scene.layout.BorderPane;
    import javafx.scene.layout.HBox;
    import javafx.stage.Modality;
    import javafx.stage.Stage;
    import javafx.stage.StageStyle;
    public class ModalDialog extends Stage {
         Stage owner;
         Stage stage;
         BorderPane root;
      public ModalDialog( Stage owner, String title){
        root = new BorderPane();
        stage = this;
        this.owner = owner;
        initModality( Modality.APPLICATION_MODAL );
        initOwner( owner );
        initStyle( StageStyle.UTILITY );
        setTitle( title );
        setContents();
      public void setContents(){
        Scene scene = new Scene(root,150,150);
        setScene(scene);
        Group groupInDialog = new Group();
        groupInDialog.getChildren().add( new Label("Really Exit ?") );
        root.setCenter( groupInDialog );
        Button yes = new Button( "Yes" );
        yes.setOnAction(new EventHandler<ActionEvent>() {
              @Override
              public void handle(ActionEvent paramT) {
                   stage.close(); // Closing the pop up.
                   owner.close(); // Closing the parent stage also.
        Button no  = new Button( "No" );
        no.setOnAction(new EventHandler<ActionEvent>() {
              @Override
              public void handle(ActionEvent paramT) {
                   stage.close(); // Closing the pop up only
        HBox buttonPane = new HBox();
        buttonPane.setSpacing(10);
        buttonPane.getChildren().addAll(yes,no);
        root.setBottom(buttonPane);
        stage.show();
    }And the main class to check this implementation is
    import javafx.application.Application;
    import javafx.event.EventHandler;
    import javafx.scene.Group;
    import javafx.scene.Scene;
    import javafx.stage.Stage;
    import javafx.stage.WindowEvent;
    public class WindowEvent06 extends Application {
      public void start(final Stage stage) throws Exception {
        Group root = new Group();
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.setTitle("WindowEvent06");
        stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
          public void handle(final WindowEvent e){
             e.consume(); // Consuming the event by default.
             new ModalDialog( stage, "Question");
        stage.show();
      public static void main(String[] args) {
        launch(args);
    }I hope the above code will give you some idea what i mean. :)
    Happy Coding !!
    Regards,
    Sai Pradeep Dandem.
    Edited by: Sai Pradeep Dandem on Jan 20, 2012 4:03 AM

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

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

  • AWT idle event thread?

    Does anyone have an example of how to create an
    AWT "busy" Dialog? I'd like to have a modal dialog
    come up that says my applet is doing some task,
    and when that task is complete, the Dialog should
    go away. So, typically, the user would not click
    anything in the dialog, it would just go away when
    the task finishes.
    What I now do is call show() from the event thread,
    and also span a new thread to do the actual work and
    when the work is complete, my new thread (not
    the AWT event thread) gets rid of the busy dialog.
    However, this seems to result in a hung UI most
    of the time with IE.
    I suspect maybe if the event thread got rid of the
    Dialog instead of my other thread the UI hang might
    not happen.
    Is there a way I can create tell AWT to run an idle
    thread (ie, when it's not doing anything)? If I could
    do that, then I could let the AWT event thread get
    rid of my dialog.
    Thank you!

    First of all, there is no way to create a modal dialog for an applet. Because the constructor of modal dialog needs a Dialog or Frame object as its owner. Unfortunately, the applet subclasses Panel that is in the hierarchy that is other than Dialog and Frame's. You can think in this way the applet does not own the browser's window.
    The dialog created by an applet sometimes get UI frozen. The reason is that the thread you created for the dialog is in the same thread group, sun.applet.AppletThreadGroup where the dialog thread can not get enough time slices to run.
    What I have done to solve this problem is to create the dialog thread under main thread group. I list the source code below for your reference.
    ThreadGroup group = Thread.currentThread().getThreadGroup();
    while(!group.getName().equals("main"))
    group = group.getParent();
    new Thread(group, this, "BusyDialog").start();

  • Kill Event thread or abort/restart main VI

    I am looking for a method of killing off an event thread once it is in the middle of executing.  A description of my problem is below (I am using labview 8.2).
    My main VI is reading my DAQ and constantly updating the main control panel with the data and logging the data at operator defined rates.
    The user can then select different functions for the system to execute using an enumeration and a Boolean control.
    When the user selects the Boolean control (run button) an event is triggered, the ENUM is read, and various sub-vi's execute to complete the function (none of the sub-vis have visible control panels all of them use some of the data from the main vi's controls/indicators passed by reference).
    The user also has a stop button.  If pressed another event is generated.  I would like to kill the run event in this case, at any point in its execution (long delays in some of the sub-vi's).  Then I can set the system back to default and continue on selecting another function in the enumeration and run button press.
    I would also considering aborting the main vi and then restarting it as long as the front panel remains open.

    I appreciate the reply.  I agree that the event cannot be killed, I have tried several "tricks".  The code does go into the stop event while the run event/sub vi is executing. 
     I had the ref to the stop button wired into the sub-vi's already.  Some of these vi's are fairly in depth, do you have a recommendation to continuously read its state without getting into every loop etc that is in the sub-vi?  I was trying not to monitor this buttons state at every point in the sub-vi's block diagrams.
    Thanks

  • Synchronize AccessBridge thread with AWT event thread?

    Hi,
    I am a beginner in Java Access Bridge.
    I am writing a program that runs with Java Web Start and uses JFC Swing. For system monitoring purpose my company uses HP OpenView. Probe Builder is used for recording a probe for the application. The probe will be run at regular intervals to check if anything is broken. As I understand Probe Builder uses Java Access Bridge to record & control the application flow.
    Without Java Access Bridge my program runs fine. But when I run it with Probe Builder I occasionally catch some exceptions that indicate that there are two threads running over my gui classes at the same time, the AWT event thread and another thread that comes from com.sun.java.accessibility.AccessBridge.run.
    Since my classes are not thread safe (like all the Swing classes) there are race conditions that result in a NullPointerException.
    My question is that how can I make sure that only one thread at a time is running over my code? Can I somehow make Java Access Bridge run with the AWT event thread? Or do I have to synchronize all my methods - I want to avoid this since I am not sure that this can be done perfectly.
    I will appreciate any help.
    Thanks
    Message was edited by:
    karneim

    Maybe there is some other way to "kill" this thread because for some specific reasons I don't think I will be able to use System.exit(). This reason is - I'm using this Java program in Lotus Notes (don't know if you have had any experience with this) and if I call System.exit() then some important clean-up (garbage collection) won't be done.

  • Wait while event thread has been removed all events

    hi,
    how can i wait while the event thread has been work out all its events in the queue? is there something like eventQueue.isEmpty();???

    Have a look at invokeLater()

  • I have movies, events, clips, etc. scattered over three macs, and would like to consolidate them in one place, hopefully in ONE library on an external HD.  How, please!

    I have movies, events, clips, etc. scattered over three macs, and would like to consolidate them in one place, hopefully in ONE library on an external HD.  How, please!

    Try forcing iPhoto to load the Library on the External Hard drive by launching it while holding down the Option key. Choose the Library on the External HD, and quit iPhoto, see if iMovie can see the Library with the iPhoto Videos contained inside.

  • Package javax.swing.event not found in import.

    I'm receiving the above error message when compiling a Java application which begins with the following import statements:
    * 1.1+Swing version.
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    My Classpath System variables are as follows:
    C:\IBMCON~1\CICS\Classes\CTGCLI~1.JAR;.;C:\PROGRA~1\MQSeries\java\lib\COMIBM~2.JAR;C:\PROGRA~1\MQSeries\java\lib\COMIBM~1.JAR;C:\PROGRA~1\MQSeries\java\lib\COMIBM~3.JAR;C:\PROGRA~1\MQSeries\tools\javaclnt\samples\en_us;C:\Program Files\SQLLIB\java\db2java.zip;C:\Program Files\SQLLIB\java\runtime.zip;C:\Program Files\SQLLIB\bin;C:\Program Files\SQLLIB\java\SQLj.zip
    I have Java(TM) 2 SDK, Standard Edition, Version 1.4.0 installed and am running Windows 2000.
    I'd appreciate any ideas as to why this compiler error occurs. Thanks very much.

    What error message?
    As stated, looks like something's not where it's supposed to be.
    Here's the search order of your classpath:
    C:\IBMCON~1\CICS\Classes\CTGCLI~1.JAR
    C:\PROGRA~1\MQSeries\java\lib\COMIBM~2.JAR
    C:\PROGRA~1\MQSeries\java\lib\COMIBM~1.JAR
    C:\PROGRA~1\MQSeries\java\lib\COMIBM~3.JAR
    C:\PROGRA~1\MQSeries\tools\javaclnt\samples\en_us
    C:\Program Files\SQLLIB\java\db2java.zip
    C:\Program Files\SQLLIB\java\runtime.zip
    C:\Program Files\SQLLIB\bin
    C:\Program Files\SQLLIB\java\SQLj.zip

  • How do you dispose a thread-handled modal dialog not thru some actions?

    The code almost looks like this:
    /* Thread that disposes the dialog when the time in seconds is "9" */
    class AboutThread extends Thread {
    private volatile Thread about;
    AboutDialog ad;
    AboutThread(AboutDialog ad) {
    this.ad = ad;
    public void stopped() {
    about = null;
    ad.dispose();
    ad = null;
    System.gc();
    public synchronized void run() {
    Thread thisThread = Thread.currentThread();
    about = thisThread;
    System.out.println("About thread is running!");
    ad.start();
    while (about == thisThread) {
    try {
    Thread.sleep(1000);
    } catch (InterruptedException ex) {
         System.err.println("Thread.sleep error: " + ex);
    String s = new String(getCurrentDateTime("s"));
    if (s.equals("9")) {
    ad.setVisible(false);
    ad.setModal(false);
    ad.setVisible(true);
    System.out.println(9);
    this.stop();
    /* Shows a dialog describing the User Log application */
    public class AboutDialog extends Dialog implements ActionListener {
    public AboutDialog(Frame parent, String title) {
         super(parent, title, false);
         Panel labelPanel = new Panel();
         labelPanel.setLayout(new BorderLayout());
         labelPanel.setBackground(Color.gray);
    JLabel jlab = new JLabel("User Log 1.0");
    jlab.setHorizontalAlignment(SwingConstants.CENTER);
    jlab.setFont(new Font("Monospaced", Font.BOLD, 28));
    JLabel jlab1 = new JLabel("Copyright(c) 2001 Soft Wares. All Rights Reserved.");
    jlab1.setHorizontalAlignment(SwingConstants.CENTER);
    labelPanel.add(jlab, "Center");
         labelPanel.add(jlab1, "South");
         add(labelPanel, "Center");
         Panel buttonPanel = new Panel();
    buttonPanel.setBackground(Color.gray);
         Button okButton = new Button("OK");
         okButton.addActionListener(this);
         buttonPanel.add(okButton);
         add(buttonPanel, "South");
         setSize(400, 130);
         setLocation(parent.getLocationOnScreen().x + 200,
              parent.getLocationOnScreen().y + 200);
    public void start() {
    show();
    public void actionPerformed(ActionEvent e) {
         setVisible(false);
         dispose();
    at.stopped();
    }

    ooops! i'm sorry. in the AboutDialog Class, it should be "super(parent, title, true)" for it to be modal.
    anyway, it seemed that posting the partial code above of the whole app is not so understandable.
    what i like to address here is that: how do i dispose or get rid of the thread-dispatched modal dialog by not making mouse clicks or any other user intervention? i wanted it to be disposed by the same thread, which dispatched it, when a certain variable value (global or local) is met. is this possible?

  • Updating component within awt-event thread of another component

    Hi,
    I'm having trouble updating (repainting) a component inside the awt-event thread of another component. The component I want to update is a JFrame with a JLabel that lists the progress of the original component's action that triggered the event. I can get the frame to pop up but it's content is never fully painted and never refreshed.
    I've tried using invokeLater() (the frame ran after the original awt-event had finished) and invokeAndWait() (blocked the original awt-event) and running the computational intensive parts of the original component's action in SwingWorker threads (no difference) but all to no avail.
    What I want to do is similar to a progress bar so I think it should possible. Any suggestions? Thanks, Matt

    Are you calling yield() or sleep(...) on your Thread?

  • 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

Maybe you are looking for

  • Problem with mmon and freespace

    Hi all, I'm using Oracle 10 XE and i have a problem: Oracle located on disc D:\ (size=93GB). The day before yesterday free space on disc is over... I have found in a folder D:\oraclexe\app\oracle\admin\xe\bdump ~100 files xe_mmon_[number].trc in size

  • BPM to get rid of polling for file adapter

    Hello, nice scenario here: We want to trigger a scenario for file to file transfer via an aRFC to be independent from the polling. Looks like this needs a BPM, which could be started via an aRFC (save e.g. the content of the RFC in a directory on the

  • How can I make the Counter move from inside text box to inside Footer?

    I am tweaking a page. At this point, I cannot move the Counter and the Email Me icon from the bottom of the text box to inside the footer like someone here said he does. Why do the Counter and the Email Me icon resist being moved? I am in Graphics mo

  • Can Co-Exist two CHARM setups for managing an Unique Landscape?

    Hi Guys We are actually migrating and Upgrading an existing Solution Manager 7.01 to 7.1 Since we are performing tests on this Sandbox system, we would like to replicate CHARM configuration and execute full integration tests against managed systems.

  • Query on Bapi

    HI This is the query on BAPi,I have got one FS on Enhancement.i.e EPOS Upload program,that means i have to upload the data from Excel sheet to sap by using BAPI.I have one BAPI Name also,i.e XBAPI_RE_CN_SALES_REP_REPORT.This was given from onsite,i a