public RobotHandler() {
   try {
     robot = new Robot();
   } catch (AWTException e) {
     e.printStackTrace();
   }
 }
Example #2
0
 public RobotBot() {
   try {
     this.robot = new Robot();
   } catch (AWTException e) {
     e.printStackTrace();
   }
 }
Example #3
0
  private void keepComputerAwake() {

    int toMoveX = (int) (Math.random() * 100);
    int toMoveY = (int) (Math.random() * 100);

    Point newMouse = MouseInfo.getPointerInfo().getLocation();

    if (newMouse.x != mouseX || newMouse.y != mouseY) {
      mouseX = newMouse.x;
      mouseY = newMouse.y;
      return;
    }

    if (robot == null) {
      try {
        robot = new Robot();
      } catch (AWTException e) {
        e.printStackTrace();
      }
    }

    robot.mouseMove(toMoveX, toMoveY);

    mouseX = toMoveX;
    mouseY = toMoveY;
  }
  private void createShadowBorder() {
    backgroundImage =
        new BufferedImage(
            getWidth() + SHADOW_WIDTH, getHeight() + SHADOW_WIDTH, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = (Graphics2D) backgroundImage.getGraphics();

    try {
      Robot robot = new Robot(getGraphicsConfiguration().getDevice());
      BufferedImage capture =
          robot.createScreenCapture(
              new Rectangle(getX(), getY(), getWidth() + SHADOW_WIDTH, getHeight() + SHADOW_WIDTH));
      g2.drawImage(capture, null, 0, 0);
    } catch (AWTException e) {
      e.printStackTrace();
    }

    BufferedImage shadow =
        new BufferedImage(
            getWidth() + SHADOW_WIDTH, getHeight() + SHADOW_WIDTH, BufferedImage.TYPE_INT_ARGB);
    Graphics graphics = shadow.getGraphics();
    graphics.setColor(new Color(0.0f, 0.0f, 0.0f, 0.3f));
    graphics.fillRoundRect(6, 6, getWidth(), getHeight(), 12, 12);

    g2.drawImage(shadow, getBlurOp(7), 0, 0);
  }
Example #5
0
 private void startRobot() {
   try {
     robot = new Robot();
   } catch (AWTException e) {
     e.printStackTrace();
   }
 }
 public PlateGUIRobot() {
   try {
     robot = new Robot();
   } catch (AWTException e) {
     e.printStackTrace();
   }
 }
Example #7
0
  private MainPanel(final JFrame frame) {
    super();
    add(check);
    setPreferredSize(new Dimension(320, 240));

    if (!SystemTray.isSupported()) {
      frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      return;
    }
    frame.addWindowListener(
        new WindowAdapter() {
          @Override
          public void windowIconified(WindowEvent e) {
            if (check.isSelected()) {
              e.getWindow().dispose();
            }
          }
        });
    // or
    // frame.addWindowStateListener(new WindowStateListener() {
    //    @Override public void windowStateChanged(WindowEvent e) {
    //        if (check.isSelected() && e.getNewState() == Frame.ICONIFIED) {
    //            e.getWindow().dispose();
    //        }
    //    }
    // });

    final SystemTray tray = SystemTray.getSystemTray();
    Dimension d = tray.getTrayIconSize();
    BufferedImage image = makeBufferedImage(new StarIcon(), d.width, d.height);
    final PopupMenu popup = new PopupMenu();
    final TrayIcon icon = new TrayIcon(image, "TRAY", popup);

    MenuItem item1 = new MenuItem("OPEN");
    item1.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            frame.setVisible(true);
          }
        });
    MenuItem item2 = new MenuItem("EXIT");
    item2.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            tray.remove(icon);
            frame.dispose();
            // frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
          }
        });
    popup.add(item1);
    popup.add(item2);

    try {
      tray.add(icon);
    } catch (AWTException e) {
      e.printStackTrace();
    }
  }
Example #8
0
  public static void captureScreen(Component Area) {

    // Find out where the user would like to save their screen shot
    String fileName = null;
    JFileChooser chooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Screen Shots", "png");
    chooser.setFileFilter(filter);
    int returnVal = chooser.showSaveDialog(null);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
      File saveFile = new File(chooser.getSelectedFile().getPath() + ".png");
      fileName = saveFile.toString();

      // Check to see if we will overwrite the file
      if (saveFile.exists()) {
        int overwrite =
            JOptionPane.showConfirmDialog(null, "File already exists, do you want to overwrite?");
        if (overwrite == JOptionPane.CANCEL_OPTION
            || overwrite == JOptionPane.CLOSED_OPTION
            || overwrite == JOptionPane.NO_OPTION) {
          return;
        }
      }
    }
    // If they didn't hit approve, return
    else {
      return;
    }

    // Determine the exact coordinates of the screen that is to be captured
    Dimension screenSize = Area.getSize();
    Rectangle screenRectangle = new Rectangle();
    screenRectangle.height = screenSize.height;
    screenRectangle.width = screenSize.width;
    screenRectangle.x = Area.getLocationOnScreen().x;
    screenRectangle.y = Area.getLocationOnScreen().y;

    // Here we have to make the GUI Thread sleep for 1/4 of a second
    // just to give the save dialog enough time to close off of the
    // screen. On slower computers they were capturing the screen
    // before the dialog was out of the way.
    try {
      Thread.currentThread();
      Thread.sleep(250);
    } catch (InterruptedException e1) {
      e1.printStackTrace();
    }

    // Attempt to capture the screen at the defined location.
    try {
      Robot robot = new Robot();
      BufferedImage image = robot.createScreenCapture(screenRectangle);
      ImageIO.write(image, "png", new File(fileName));
    } catch (AWTException e) {
      e.printStackTrace();
    } catch (IOException e) {
      JOptionPane.showMessageDialog(null, "Could not save screen shoot at: " + fileName);
      e.printStackTrace();
    }
  }
Example #9
0
 public ScreenshotMaker() {
   try {
     robot = new Robot();
   } catch (AWTException e) {
     e.printStackTrace();
   }
   rectangle = new Rectangle(0, 0, 1000, 800);
 }
 // Set if the application is in editing mode based on the state of the shift key
 public void setEditingMode() {
   try {
     Robot robot = new Robot();
     robot.keyRelease(KeyEvent.VK_SHIFT);
   } catch (AWTException e) {
     e.printStackTrace();
   }
 }
Example #11
0
 public Tests(Wiimote wim) {
   wiimote = wim;
   wiimote.addWiiMoteEventListeners(this);
   try {
     robot = new Robot();
   } catch (AWTException e) {
     e.printStackTrace();
   }
 }
 /** 按Esc键的封装方法 */
 public static void pressEscKey() {
   Robot robot = null;
   try {
     robot = new Robot();
   } catch (AWTException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   robot.keyPress(KeyEvent.VK_ESCAPE);
   robot.keyRelease(KeyEvent.VK_ESCAPE);
 }
 public static void main(String... args) {
   RobotHero robot = new RobotHero();
   try {
     robot.run();
   } catch (InterruptedException e) {
     System.out.println("Excecution interrupted - exiting");
   } catch (AWTException e) {
     // This exception can only really happen as a result
     // of trying to run this CLI in a very non-standard way
     e.printStackTrace();
   }
 }
Example #14
0
  /**
   * Creates an instance of <tt>TransparentBackground</tt> by specifying the parent <tt>Window</tt>
   * - this is the window that should be made transparent.
   *
   * @param window The parent <tt>Window</tt>
   */
  public TransparentBackground(Window window) {
    this.window = window;

    Robot rbt;
    try {
      rbt = new Robot();
    } catch (AWTException e) {
      e.printStackTrace();
      rbt = null;
    }
    this.robot = rbt;
  }
Example #15
0
  protected void setUp() throws Exception {
    StorageWrapper.deleteFromClient("cs320.patient");
    cont = DisplayController.GetInstance();

    cont.main(null);
    loginDisplay = (LoginDisplay) DisplayController.GetInstance().getCurrentDisplay();
    // DisplayController.main(null);
    try {
      ace = new HelpSR();
    } catch (AWTException e) {
      e.printStackTrace();
    }
  }
  public static void main(String s[]) {

    // Getting save directory
    String saveDir;
    if (s.length > 0) {
      saveDir = s[0];
    } else {
      saveDir =
          JOptionPane.showInputDialog(
              null,
              "Please enter directory where "
                  + "the images is/will be saved\n\n"
                  + "Also possible to specifiy as argument 1 when "
                  + "running this program.",
              "l:\\webcamtest");
    }

    String layout = "";
    if (s.length > 1) {
      layout = s[1];
    }

    // Move mouse to the point 5000,5000 px (out of the screen)
    Robot rob;
    try {
      rob = new Robot();
      rob.setAutoDelay(500); // 0,5 s
      rob.mouseMove(5000, 5000);
    } catch (AWTException e) {
      e.printStackTrace();
    }

    // Make the main window
    JFrame frame = new JFrame();
    frame.setAlwaysOnTop(true);
    frame.setTitle(
        "Webcam capture and imagefading - "
            + "Vitenfabrikken Jærmuseet - "
            + "made by Hallvard Nygård - "
            + "Vitenfabrikken.no / Jaermuseet.no");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.setUndecorated(true);

    WebcamCaptureAndFadePanel panel = new WebcamCaptureAndFadePanel(saveDir, layout);
    frame.getContentPane().add(panel);
    frame.addKeyListener(panel);
    frame.pack();

    frame.setVisible(true);
  }
  @Override
  protected void initialize() {
    window.requestFocusInWindow();

    // Replace the default keyboard input with DyehardKeyboard
    window.removeKeyListener(keyboard);
    keyboard = new DyehardKeyboard();
    window.addKeyListener(keyboard);

    window.addMouseListener(mouse);

    resources.setClassInJar(this);

    state = State.BEGIN;
    GameState.TargetDistance = Configuration.worldMapLength;
    world = new GameWorld();

    // preload sound/music, and play bg music
    DyeHardSound.playBgMusic();

    hero = new Hero();

    // move mouse to where center of hero is
    try {
      Robot robot = new Robot();

      robot.mouseMove(
          window.getLocationOnScreen().x
              + (int) (hero.center.getX() * window.getWidth() / BaseCode.world.getWidth()),
          window.getLocationOnScreen().y
              + window.getHeight()
              - (int) (hero.center.getX() * window.getWidth() / BaseCode.world.getWidth()));
    } catch (AWTException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    //
    // hero.registerWeapon(new SpreadFireWeapon(hero));
    // hero.registerWeapon(new OverHeatWeapon(hero));
    // hero.registerWeapon(new LimitedAmmoWeapon(hero));

    world.initialize(hero);

    new DeveloperControls(hero);

    Stargate.addColor(Colors.Yellow);

    timer = new Timer(2000);
  }
 /**
  * 将指定字符串设为剪切板的内容,然后执行粘贴操作 将页面焦点切换到输入框后,将指定内容粘贴到输入框中
  *
  * @param string
  */
 public static void setAndctrlVClipboardData(String string) {
   StringSelection stringSelection = new StringSelection(string);
   Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
   Robot robot = null;
   try {
     robot = new Robot();
   } catch (AWTException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   robot.keyPress(KeyEvent.VK_CONTROL);
   robot.keyPress(KeyEvent.VK_V);
   robot.keyRelease(KeyEvent.VK_V);
   robot.keyRelease(KeyEvent.VK_CONTROL);
 }
Example #19
0
  public void install() {
    try {
      if (trayIcon == null && SystemTray.isSupported()) {
        SystemTray systemTray = SystemTray.getSystemTray();
        Dimension size = systemTray.getTrayIconSize();
        trayIcon = createTrayIcon(size);
        systemTray.add(trayIcon);

        JPopupMenu popup = new JPopupMenu();
        trayIcon.setJPopupMenu(popup);
        createPopup(popup);
      }
    } catch (AWTException e) {
      e.printStackTrace();
    }
  }
Example #20
0
  /**
   * Gets the local machine's Java robot object.
   *
   * @return
   */
  private Robot getRobot() {
    Robot r = null;
    final GraphicsDevice[] screenDevices =
        GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices();
    // if invalid screen device number... just set to 0
    if (!(deviceToControl >= 0 && deviceToControl < screenDevices.length)) {
      deviceToControl = 0;
    }

    // create it for the specified device
    try {
      r = new Robot(screenDevices[deviceToControl]);
    } catch (AWTException e) {
      e.printStackTrace();
    }
    return r;
  }
  public void takeScreenShot() {
    BufferedImage screencapture;

    try {
      screencapture = new Robot().createScreenCapture(guiFrame.getBounds());

      File file = new File(getMojamDir() + "/" + "screenShot" + sShotCounter++ + ".png");
      while (file.exists()) {
        file = new File(getMojamDir() + "/" + "screenShot" + sShotCounter++ + ".png");
      }

      ImageIO.write(screencapture, "png", file);
    } catch (AWTException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Example #22
0
  public Tray() {

    if (SystemTray.isSupported()) {

      EventHandler EH = new EventHandler();

      SystemTray Tray = SystemTray.getSystemTray();
      Toolkit tk = Toolkit.getDefaultToolkit();
      Image img =
          tk.getImage(
              System.getProperty("user.dir")
                  + fileSeparator
                  + "res"
                  + fileSeparator
                  + "notica.png");

      PopupMenu menu = new PopupMenu();
      MenuItem action = new MenuItem("Nueva Nota");
      MenuItem Close = new MenuItem("Cerrar");

      action.addActionListener(EH.addNote());
      Close.addActionListener(EH.Cerrar());

      menu.add(action);
      menu.add(Close);

      TrayIcon ti = new TrayIcon(img, "Knote 1.0", menu);
      ti.setImageAutoSize(true);

      try {
        Tray.add(ti);

      } catch (AWTException ex) {
        ex.printStackTrace();
        System.out.println("Error AWTException " + ex.getMessage());
      }

    } else {
      System.out.println("System Tray is not supported");
      return;
    }
  }
Example #23
0
  public void screenshot() {

    if (System.currentTimeMillis() - ultimaFoto > 1000) {

      try {
        Robot robot = new Robot();
        Rectangle captureSize = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
        BufferedImage bufferedImage = robot.createScreenCapture(captureSize);

        File outputfile =
            new File(
                System.getProperty("user.home") + "\\Desktop\\ScreenShot" + ultimaFoto + ".jpg");
        ImageIO.write(bufferedImage, "jpg", outputfile);
      } catch (IOException e) {

      } catch (AWTException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      ultimaFoto = System.currentTimeMillis();
    }
  }
 @Test
 public void testEntrarComLoginQualquer() {
   try {
     // fail("Not yet implemented");
     try {
       Thread.sleep(3000);
     } catch (Exception e) {
     }
     JButton botaoEntrar = telaLogin.getEntrar();
     Robot r = new Robot();
     r.delay(3000);
     Point p = botaoEntrar.getLocationOnScreen();
     r.mouseMove(p.x + botaoEntrar.getWidth() / 2, p.y + botaoEntrar.getHeight() / 2);
     r.mousePress(InputEvent.BUTTON1_MASK);
     r.delay(3000);
     r.mouseRelease(InputEvent.BUTTON1_MASK);
     r.delay(3000);
   } catch (AWTException exc) {
     exc.printStackTrace();
     fail("awt exception no teste da telaLogin clicar botao entrar");
   }
 }
Example #25
0
 @Override
 public void run() {
   while (running) {
     GemGrid grid = new GemGrid();
     Solver solver = new Solver(grid);
     try {
       solver.generateGrid();
     } catch (AWTException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     }
   }
   while (!running) {
     try {
       Thread.sleep(2000);
     } catch (InterruptedException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     }
   }
   run();
 }
Example #26
0
 public void run() {
   BufferedWriter out = null;
   try {
     out = new BufferedWriter(new FileWriter("output"));
   } catch (IOException e1) {
     // TODO Auto-generated catch block
     e1.printStackTrace();
   }
   Robot robot = null;
   try {
     robot = new Robot();
   } catch (AWTException e1) {
     // TODO Auto-generated catch block
     e1.printStackTrace();
   }
   while (true) {
     try {
       int x = in.readInt();
       int y = 1000 - in.readInt() * (-1);
       int clicked = in.readInt();
       if (clicked == YES) {
         robot.mousePress(InputEvent.BUTTON1_MASK);
         System.out.println("YES");
       } else {
         robot.mouseRelease(InputEvent.BUTTON1_MASK);
         System.out.println("NO");
       }
       // apply kalman filter here
       kalmanFilter(x, y); // this would change the values of x2 and y2
       robot.mouseMove((int) x2, (int) y2);
       out.write(x2 + " " + y2 + "\n");
       out.flush();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
 }
Example #27
0
  public static void main(String args[]) {
    Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
    BufferedImage capture;
    try {
      File ts = new File("timestamps.txt");
      FileWriter tsWriter;

      long previousSleepTime = 0;

      for (int i = Constants.START;
          i < Constants.START + 3600 * Constants.FPS * Constants.HOURS;
          ++i) {
        System.out.println(i);
        tsWriter = new FileWriter(ts, previousSleepTime > 0);
        if (previousSleepTime > 0) {
          previousSleepTime = System.currentTimeMillis() - previousSleepTime;
        }
        long timeOut = 1000 / Constants.FPS - previousSleepTime;
        Thread.sleep(timeOut > 0 ? timeOut : 0);
        previousSleepTime = System.currentTimeMillis();
        capture = new Robot().createScreenCapture(screenRect);

        new File(new Integer(i / Constants.FILES_PER_FOLDER).toString()).mkdir();
        String frameFileName = (i / Constants.FILES_PER_FOLDER) + "\\test" + i + ".jpg";
        ImageIO.write(capture.getSubimage(100, 100, 640, 480), "jpg", new File(frameFileName));

        tsWriter.write(frameFileName + " " + System.currentTimeMillis() + NEW_LINE);
        tsWriter.close();
      }
    } catch (AWTException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
  public void init() {
    try {
      robot = new Robot();
    } catch (AWTException ex) {
      ex.printStackTrace();
      throw new RuntimeException(ex);
    }
    this.setLayout(new BorderLayout());

    target.setBackground(Color.green);
    target.setName("GreenBox"); // for the ease of debug
    target.setPreferredSize(new Dimension(100, 100));
    String toolkit = Toolkit.getDefaultToolkit().getClass().getName();

    // on X systems two buttons are reserved for wheel though they are countable by MouseInfo.
    int buttonsNumber =
        toolkit.equals("sun.awt.windows.WToolkit")
            ? MouseInfo.getNumberOfButtons()
            : MouseInfo.getNumberOfButtons() - 2;

    for (int i = 0; i < 8; i++) {
      buttonNumber.add("BUTTON" + (i + 1) + "_MASK");
    }

    pressOn.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            System.out.println("Now pressing : " + (buttonNumber.getSelectedIndex() + 1));

            Timer timer = new Timer();
            TimerTask robotInteraction =
                new TimerTask() {
                  public void run() {
                    robot.mouseMove(updateTargetLocation().x, updateTargetLocation().y);
                    robot.mousePress(getMask(buttonNumber.getSelectedIndex() + 1));
                  }
                };
            timer.schedule(robotInteraction, SEND_DELAY);
          }
        });

    releaseOn.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            System.out.println("Now releasing : " + (buttonNumber.getSelectedIndex() + 1));
            Timer timer = new Timer();
            TimerTask robotInteraction =
                new TimerTask() {
                  public void run() {
                    robot.mouseMove(updateTargetLocation().x, updateTargetLocation().y);
                    robot.mouseRelease(getMask(buttonNumber.getSelectedIndex() + 1));
                  }
                };
            timer.schedule(robotInteraction, SEND_DELAY);
          }
        });

    clickOn.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            System.out.println("Now clicking : " + (buttonNumber.getSelectedIndex() + 1));
            Timer timer = new Timer();
            TimerTask robotInteraction =
                new TimerTask() {
                  public void run() {
                    robot.mouseMove(updateTargetLocation().x, updateTargetLocation().y);
                    robot.mousePress(getMask(buttonNumber.getSelectedIndex() + 1));
                    robot.mouseRelease(getMask(buttonNumber.getSelectedIndex() + 1));
                  }
                };
            timer.schedule(robotInteraction, SEND_DELAY);
          }
        });
    target.addMouseListener(
        new MouseAdapter() {
          public void mousePressed(MouseEvent e) {
            Sysout.println("" + e);
          }

          public void mouseReleased(MouseEvent e) {
            Sysout.println("" + e);
          }

          public void mouseClicked(MouseEvent e) {
            Sysout.println("" + e);
          }
        });

    String[] instructions = {
      "Do provide an instruction to the robot by",
      "choosing the button number to act and ",
      "pressing appropriate java.awt.Button on the left.",
      "Inspect an output in the TextArea below.",
      "Please don't generate non-natural sequences like Release-Release, etc.",
      "If you use keyboard be sure that you released the keyboard shortly.",
      "If events are generated well press Pass, otherwise Fail."
    };
    Sysout.createDialogWithInstructions(instructions);
  } // End  init()
Example #29
0
  @Override
  public void mouseClicked(MouseEvent arg0) {
    // LEFT BUTTON
    // toggle between normal and reverse drive mode
    if (arg0.getButton() == MouseEvent.BUTTON1 && arg0.getClickCount() == 2) {
      // reverse drive direction selected
      isNormalDrive = !isNormalDrive;

      // apply reverse compass map if reverse drive is selected
      if (isNormalDrive) lbBkg.setIcon(new ImageIcon("images/kAPPframe.png"));
      else lbBkg.setIcon(new ImageIcon("images/kAPPframeRev.png"));

      // recalculate KAPP icon position within the toggled compass map
      xLab += (int) (arg0.getX() - wLab / 2); /* current */
      yLab += (int) (arg0.getY() - hLab / 2);
      int xCmd = -(xLab - xRef);
      int yCmd = -(yRef - yLab);
      xLab = xCmd + xRef; /* new */
      yLab = yRef - yCmd;

      // redraw kAPP icon
      lbKAPP.setBounds(xLab, yLab, wLab, hLab);
      lbKAPP.repaint(xLab, yLab, wLab, hLab);

      // drag the mouse pointer on top of the KAPP icon
      xFrm = frame.getX();
      yFrm = frame.getY();
      int newMouseX = xLab + xBrd + (int) (wLab / 2) + xFrm;
      int newMouseY = yLab + 4 * yBrd + (int) (hLab / 2) + yFrm;
      try {
        Robot robot = new Robot();
        robot.mouseMove(newMouseX, newMouseY);
      } catch (AWTException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      }
    }

    // WHEEL BUTTON
    // increase/decrease wheel speed (in calibration only)
    if (arg0.getButton() == MouseEvent.BUTTON2 && cmdCalibrate) {
      DE.encodeSpecialCommands(DataExchange.SPDLEV_CMD);
      DE.incSpeedLevel();
      lbKAPP.setToolTipText("SPEED LEVEL: " + DE.getSpeedLevel());
    }

    // RIGHT BUTTON
    // send START/STOP special commands
    if (arg0.getButton() == MouseEvent.BUTTON3) {
      if (arg0.getClickCount() >= 2) {
        // toggle STOP/START command:
        // true => STOP_CMD; false => START_CMD
        cmdStartStop = !cmdStartStop;

        if (cmdStartStop) {
          DE.encodeSpecialCommands(DataExchange.STOP_CMD);
          lbKAPP.setToolTipText("*STOP*");
          frame.setIconImage(Toolkit.getDefaultToolkit().getImage("images/kAPPstop.png"));

        } else {
          DE.encodeSpecialCommands(DataExchange.START_CMD);
          cmdCalibrate = false;
          lbKAPP.setToolTipText("*GO*");
          frame.setIconImage(Toolkit.getDefaultToolkit().getImage("images/kAPPgo.png"));
        }
      }

      // send CALIBRATE special command
      if (cmdStartStop && (arg0.getClickCount() == 1)) {
        // if the Stop command is issued, perform command Motors calibration
        cmdCalibrate = true;
        DE.encodeSpecialCommands(DataExchange.CAL_CMD);
        lbKAPP.setToolTipText("*CALIBRATION*");
        frame.setIconImage(Toolkit.getDefaultToolkit().getImage("images/kAPPcal.png"));
      }
    }
  }
Example #30
0
  public static void main(String[] args) {
    System.out.println(ResourceUsage.getStatus());
    final String ipAddress = Util.getIp();
    final Thread listener;
    final SocketListener socketListener = new SocketListener();
    listener = new Thread(socketListener);
    if (!SystemTray.isSupported()) {
      System.err.println("System tray is not supported.");
      return;
    }

    SystemTray systemTray = SystemTray.getSystemTray();

    Image image =
        Toolkit.getDefaultToolkit().getImage(ServiceDriver.class.getResource("pause.png"));

    final TrayIcon trayIcon = new TrayIcon(image);

    final PopupMenu trayPopupMenu = new PopupMenu();

    MenuItem startService = new MenuItem("Start Service");
    startService.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(
                null, "Service Started", "Surrogate Service", JOptionPane.INFORMATION_MESSAGE);
            try {
              listener.start();
              Image image =
                  Toolkit.getDefaultToolkit()
                      .getImage(ServiceDriver.class.getResource("cyber.gif"));
              trayIcon.setImage(image);
            } catch (Exception err) {
              Image image =
                  Toolkit.getDefaultToolkit()
                      .getImage(ServiceDriver.class.getResource("cyber.gif"));
              trayIcon.setImage(image);
              socketListener.resume();
            }
          }
        });
    trayPopupMenu.add(startService);

    MenuItem action = new MenuItem("Stop Service");
    action.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(
                null, "Service Stopped", "Surrogate Service", JOptionPane.INFORMATION_MESSAGE);
            try {
              socketListener.pause();
              Image image =
                  Toolkit.getDefaultToolkit()
                      .getImage(ServiceDriver.class.getResource("pause.png"));
              trayIcon.setImage(image);
            } catch (Exception e1) {
              System.err.println("Service has not stared yet");
            }
          }
        });
    trayPopupMenu.add(action);

    MenuItem close = new MenuItem("Close");
    close.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            System.exit(0);
          }
        });
    trayPopupMenu.add(close);

    trayIcon.setPopupMenu(trayPopupMenu);

    trayIcon.addMouseMotionListener(
        new MouseMotionAdapter() {
          @Override
          public void mouseMoved(MouseEvent e) {
            trayIcon.setToolTip(Util.getStatus(ipAddress));
          }
        });
    trayIcon.setImageAutoSize(true);

    try {
      systemTray.add(trayIcon);
    } catch (AWTException awtException) {
      awtException.printStackTrace();
    }
  }