Home
Categories
Dictionary
Download
Project Details
Changes Log
Who We Are
FAQ
License

Handling Input events in Unit Tests



This article explains how to handle input events in Unit Tests.

Handling Mouse events

To test the J661 Server behavior with Mouse events (for example Mouse clicks), you should normally use the Awt Robot class. The trick for Mouse events is to compute where to apply the event. Note that:
  • You must take care to wait until the event queue has been taken into account
  • There is no direct click event on the Robot class, but you can create a a click by generating a Press then a Release event

Handling Mouse events in JavaFX

      // We create a Mouse event by using the Robot. Warning that the mouse position will be forced on the screen
      final Pane pane = (Pane) layer.getRootWindow(RendererKey.DEFAULT);
      GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
      try {
         final Robot robot = new Robot(ge.getDefaultScreenDevice());
         SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
               int pos = PainterUtils.floatToPixelsX(5000f);
               javafx.geometry.Point2D p = pane.localToScreen(pos, pos);
               robot.mouseMove((int) p.getX(), (int) p.getY());
               robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
               robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
            }
         });
      } catch (Exception e) {
         e.printStackTrace();
      }
      // just to be sure that the event queue is taken into account
      try {
         Thread.sleep(200);
      } catch (InterruptedException ex) {
         ex.printStackTrace();
      }

Handling Mouse events in Swing

      final Container cont = (Container) display.getRenderer();
      // We create a Mouse event by using the Robot. Warning that the mouse position will be forced on the screen
      GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
      try {
         final Robot robot = new Robot(ge.getDefaultScreenDevice());
         SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
               int pos = PainterUtils.floatToPixelsX(5000f);
               Point p = new Point(pos, pos);
               SwingUtilities.convertPointToScreen(p, cont);
               robot.mouseMove(p.x, p.y);
            }
         });
      } catch (Exception e) {
         e.printStackTrace();
      }
      // just to be sure that the event queue is taken into account
      try {
         Thread.sleep(200);
      } catch (InterruptedException ex) {
         ex.printStackTrace();
      }

Categories: dev | junit

Copyright 2016-2017 Dassault Aviation. All Rights Reserved. Documentation and source under the LGPL v2 licence