0

I am quite new to Java and wanted to write a program that took keyboard inputs on my computer and turned them into exact mouse coordinates and then clicks. After researching for a while, I found the best way to do this was via the KeyListener interface to handle looking for the button presses and then an object of the Robot class to handle moving the mouse and clicking. After some basic tests using a few tutorials online that use JFrame, I tried to first create my Robot object to move the mouse, and then tell KeyTyped to call the mouseMove method each time q and a were pressed, but upon running the program, I only get errors saying that control cannot be resolved. What am I missing here?

import java.awt.*;
import java.awt.event.*;
import java.util.Scanner;

public class Main implements KeyListener{

    public static void main(String[] args) throws AWTException{
        Robot control = new Robot();
    }

    @Override
    public void keyTyped(KeyEvent e) {
        switch(e.getKeyChar()) {
            case 'q': control.mouseMove(20, 20);
                break;
            case 'a': control.mouseMove(60, 60);
                break;
        }
    }

    @Override
    public void keyPressed(KeyEvent e) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void keyReleased(KeyEvent e) {
        // TODO Auto-generated method stub
        
    }

}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • You defined `control` as a **local variable** in method `main`, while to be accessible in instance methods, it should be a **field** in class `Main`. Also, your `main` method currently effectively does nothing. – Mark Rotteveel Oct 16 '22 at 07:03
  • local variables, like `control` in your code, are only *known* in the block (or sub-blocks) where they are declared (same is valid for parameters like `args` or `e`, only *known* inside the method) - also you need to added the `KeyListener` to an GUI component and it will only get events if that component has the focus (alternative `Toolkit.addAWTEventListener`) – user16320675 Oct 16 '22 at 07:57
  • @user16320675, is there any way to listen for keypresses when a GUI component doesn't have the focus? (assuming that by focus you mean the component is currently the active window on the computer) – Ty Merriam Oct 16 '22 at 22:11

0 Answers0