I'm trying to make a program (in Java) that, upon pressing a key, highlights the text under your cursor, copies it, pastes it into a new tab, and searches, all using the java.awt.Robot package.
It works fine the first time, but when I press the starting key a second time, it moves the mouse back to the given coordinates first, then runs the rest of the program.
This is a problem because when it tries to triple-click to highlight text, it instead opens 3 new tabs.
Can someone please tell me what's going on?
public class Search implements KeyListener{
JFrame frame;
public Search() throws AWTException {
Robot bot = new Robot();
JFrame frame = new JFrame("Search");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
frame.setFocusable(true);
frame.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@SuppressWarnings("deprecation")
@Override
public void keyPressed(KeyEvent e) {
int keycode = e.getKeyCode();
switch(keycode) {
case KeyEvent.VK_N:
try {
bot.mousePress(MouseEvent.BUTTON1_MASK);
Thread.sleep(100);
bot.mouseRelease(MouseEvent.BUTTON1_MASK);
Thread.sleep(100);
bot.mousePress(MouseEvent.BUTTON1_MASK);
Thread.sleep(100);
bot.mouseRelease(MouseEvent.BUTTON1_MASK);
Thread.sleep(100);
bot.mousePress(MouseEvent.BUTTON1_MASK);
Thread.sleep(100);
bot.mouseRelease(MouseEvent.BUTTON1_MASK);
Thread.sleep(200);
bot.keyPress(KeyEvent.VK_META);
Thread.sleep(100);
bot.keyPress(KeyEvent.VK_C);
Thread.sleep(100);
bot.keyRelease(KeyEvent.VK_C);
Thread.sleep(100);
bot.keyRelease(KeyEvent.VK_META);
Thread.sleep(200);
bot.mouseMove(1430, 100);
Thread.sleep(200);
bot.mousePress(MouseEvent.BUTTON1_MASK);
Thread.sleep(100);
bot.mouseRelease(MouseEvent.BUTTON1_MASK);
Thread.sleep(200);
bot.keyPress(KeyEvent.VK_META);
Thread.sleep(100);
bot.keyPress(KeyEvent.VK_V);
Thread.sleep(100);
bot.keyRelease(KeyEvent.VK_V);
Thread.sleep(100);
bot.keyRelease(KeyEvent.VK_META);
Thread.sleep(200);
bot.keyPress(KeyEvent.VK_ENTER);
Thread.sleep(100);
bot.keyRelease(KeyEvent.VK_ENTER);
} catch (InterruptedException e1) {
System.out.println("Catch");
e1.printStackTrace();
}
}
}
What I have tried:
Thread.sleep(150)
Browsing Stack Overflow posts for about an hour