Java - Robot Class


SUBMITTED BY: Guest

DATE: July 14, 2013, 10:59 p.m.

FORMAT: Text only

SIZE: 2.2 kB

HITS: 5609

  1. import java.awt.AWTException;
  2. import java.awt.Dimension;
  3. import java.awt.Rectangle;
  4. import java.awt.Robot;
  5. import java.awt.Toolkit;
  6. import java.awt.event.KeyEvent;
  7. import java.awt.image.BufferedImage;
  8. import java.io.File;
  9. import java.io.IOException;
  10. import javax.imageio.ImageIO;
  11. public class RobotTest {
  12. Robot robot;
  13. public RobotTest() {
  14. try {
  15. robot = new Robot();
  16. } catch (AWTException e) {
  17. System.err.println("Co ten robot wyprawia?!");
  18. e.printStackTrace();
  19. }
  20. }
  21. /**
  22. * Metoda drukuje tekst "Hello World"
  23. */
  24. public void printText() {
  25. int[] text = {KeyEvent.VK_H, KeyEvent.VK_E, KeyEvent.VK_L, KeyEvent.VK_L, KeyEvent.VK_O, KeyEvent.VK_SPACE,
  26. KeyEvent.VK_W, KeyEvent.VK_O, KeyEvent.VK_R, KeyEvent.VK_L, KeyEvent.VK_D};
  27. //pętla - wciśnięcie przycisku i przerwa na 200ms
  28. for(int i=0; i<text.length; i++) {
  29. robot.keyPress(text[i]);
  30. robot.delay(200);
  31. }
  32. }
  33. /**
  34. * Metoda robi screenshot ekranu i zapisuje go na dysku
  35. */
  36. public void screenCapture() {
  37. //pobieramy rozmiar ekranu i tworzymy Rectangle
  38. Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
  39. Rectangle rectangle = new Rectangle(dimension);
  40. //robimy screenshot z utworzonego obszaru
  41. BufferedImage screen = robot.createScreenCapture(rectangle);
  42. try {
  43. ImageIO.write(screen, "jpg", new File("screenshot.jpg"));
  44. } catch (IOException e) {
  45. System.err.println("Błąd zapisu obrazu");
  46. e.printStackTrace();
  47. }
  48. }
  49. /**
  50. * Testujemy czy działa
  51. */
  52. public static void main(String[] args) {
  53. RobotTest test = new RobotTest();
  54. test.robot.delay(3000);
  55. test.printText();
  56. test.screenCapture();
  57. }
  58. }
  59. //Czytaj więcej na: http://javastart.pl/klasy/klasa-robot/page/2/#ixzz2Z3yiDMYo

comments powered by Disqus