In Java, there is one interesting class that provides control of the mouse cursor and keyboard. This is a Robot class.

Can you please tell how you can interrupt the work of the cycle in which the robot is working. For example, by pressing a button on the keyboard.

import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import javax.swing.*; class myFrame extends JFrame { private Robot robot; private JButton bt1; public myFrame() { setTitle("Robot"); JPanel panel = new JPanel(); GraphicsEnvironment env = GraphicsEnvironment .getLocalGraphicsEnvironment(); GraphicsDevice screen = env.getDefaultScreenDevice(); try { robot = new Robot(screen); } catch (AWTException ex) { } bt1 = new JButton("Start"); panel.add(bt1); bt1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { for (int i = 0; i < 100; i++) // здСсь ΠΈ происходят всС дСйствиС // с нашим Ρ€ΠΎΠ±ΠΎΡ‚ΠΎΠΌ { robot.mouseMove(500, 500 + 15 * i); // Π΄Π²ΠΈΠ³Π°Π΅ΠΌ ΠΌΡ‹ΡˆΠΊΡƒ Π½Π° robot.delay(300); // Π·Π°Π΄Π°Π½Π½ΡƒΡŽ ΠΊΠΎΠΎΡ€Π΄ΠΈΠ½Π°Ρ‚Ρƒ robot.mousePress(InputEvent.BUTTON1_MASK); // Π½Π°ΠΆΠΈΠΌΠ°Π΅ΠΌ Π»Π΅Π²ΡƒΡŽ // ΠΊΠ½ΠΎΠΏΠΊΡƒ ΠΌΡ‹ΡˆΠΈ robot.delay(300); // 300 миллисСкундная ΠΏΠ°ΡƒΠ·Π° robot.mouseRelease(InputEvent.BUTTON1_MASK); // ΠΎΡ‚ΠΆΠΈΠΌΠ°Π΅ΠΌ // Π»Π΅Π²ΡƒΡŽ // ΠΊΠ½ΠΎΠΏΠΊΡƒ // ΠΌΡ‹ΡˆΠΈ robot.delay(300); robot.keyPress('O'); // Π½Π°ΠΆΠΈΠΌΠ°Π΅ΠΌ ΠΊΠ½ΠΎΠΏΡƒ 'O' с ΠΊΠ»Π°Π²ΠΈΠ°Ρ‚ΡƒΡ€Ρ‹ robot.keyRelease('O'); // ΠΎΡ‚ΠΆΠΈΠΌΠ°Π΅ΠΌ ΠΊΠ½ΠΎΠΏΡƒ 'O' с ΠΊΠ»Π°Π²ΠΈΠ°Ρ‚ΡƒΡ€Ρ‹ robot.delay(300); robot.keyPress(KeyEvent.VK_DOWN); // Π½Π°ΠΆΠΈΠΌΠ°Π΅ΠΌ ΠΊΠ½ΠΎΠΏΡƒ 'DOWN' с ΠΊΠ»Π°Π²ΠΈΠ°Ρ‚ΡƒΡ€Ρ‹ robot.keyPress(KeyEvent.VK_DOWN); robot.keyPress(KeyEvent.VK_DOWN); } } }); Container pane = getContentPane(); pane.add(panel); pack(); } } public class MyRobot { public static void main(String[] args) { myFrame frame = new myFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } 
  • one
    Honestly, I doubt that this is correct, but I would advise you to move the button handler to a separate thread, and then, at the touch of a button, "Stop", for example, stop this thread. - delphist007
  • And the usual breakpoint is no longer in fashion, @ delphist007? - Salivan
  • So in the end, it will turn out to do break after the Interupted flag has been set on the Interupted (which needs to be checked). - delphist007

0