I spent two hours for the past three days researching and cannot figure this out.
This is a simple program that clicks the left mouse button every 2.5 Seconds 50 times and then the program ends. But sometimes I want to end the program sooner by pressing the escape key (not mouse).
How do I end the program by clicking the escape button? I don't know what I am doing wrong. If possible please provide code because I am new to Java and don't understand Java terminology well. Thank you for the help.
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class TestClass implements KeyListener, ActionListener
{
static boolean exit = false;
public static void main(String[] args) throws AWTException
{
//Creates robot class
Robot r = new Robot();
for(int x = 1; x < 50; x++)
{
//moves mouse to a cretain point on the screen
r.mouseMove(789, 326);
//robot class presses the mouse then realases every 2.5 Seconds
r.mousePress(InputEvent.BUTTON1_MASK);
r.mouseRelease(InputEvent.BUTTON1_MASK);
r.delay(2500);
System.out.println("This the " + x + "th time.");
}
}
//KeyLisener stuff
@Override
public void keyPressed(KeyEvent e)
{
// TODO Auto-generated method stub
if(e.getKeyCode() == KeyEvent.VK_ESCAPE)
{
System.out.println("The key has been pressed");
System.exit(0);
}
}
@Override
public void keyReleased(KeyEvent e){}
@Override
public void keyTyped(KeyEvent e){}
// Action Performed stuff
@Override
public void actionPerformed(ActionEvent arg0)
{
// TODO Auto-generated method stub
if (exit = true)
{
System.exit(0);
}
}
}