Search code examples
javaclassawtawtrobot

Java Robot - Class functions issue


I am trying to make a separate class for the Java AWT Robot to use with projects but i am having trouble setting it up how i would like as all of the examples I have found online seem to pack the code into a single .java file instead.

My code works fine however I am wondering if I could setup the functions in a nicer way.

The code for the RobotLib.java class is as follows:

package com.z;

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

    public class RobotLib {

    private static Robot robot;

    // Press Function
    public void Press(int key, int time){ 
        try {
        Robot robot = new Robot();
            robot.keyPress(key);
            robot.delay(time);
            robot.keyRelease(key);

        } catch (AWTException e) {
            e.printStackTrace();
        }
    } 

}

And my Example.java code is:

package com.z;

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

public class Example {

    public static void main(String[] args) {

        RobotLib robot = new RobotLib();

        robot.Press(KeyEvent.VK_A,100); // type a

    }
}

With the RobotLib.java class I was wondering if it's possible to have the functions without wrapping them with try/catch and new Robot() so instead of the above version it would be something like this instead:

public void Press(int key, int time){ 
    robot.keyPress(key);
    robot.delay(time);
    robot.keyRelease(key);
}

The try/catch and new Robot() seem to be required however and if I take those away I get errors like this:

Exception in thread "main" java.lang.NullPointerException
    at com.z.RobotLib.Press(RobotLib.java:35)
    at com.z.Example.main(Example.java:14)

I am quite new to Java coding and might be setting up the class the wrong way, is there a way to fix that error or have the functions how I want?


Solution

  • I just found a way to do what i wanted using a modified version of the code Raskolnikov posted, it allows shorter versions of the function like i wanted:

    public class RobotLib {
    
    private static Robot robot;
    
    public RobotLib(){
      try {
        robot = new Robot();
    } catch (AWTException e) {
        e.printStackTrace();
    }
    }
    
    // Press Function
    public void Press(int key, int time){ 
        robot.keyPress(key);
        robot.delay(time);
        robot.keyRelease(key);
    } 
    
    }