Search code examples
javaawtawtrobot

Java: simulate keypresses when mouse clicked?


So, I'm fairly new to programming and I like to fiddle with it and one day my friend asked me to make a program where when you click, "ctrl" and "s" would be "pressed". I looked at lots of forums trying to make a functional code but, since I'm new to Java, I only got separate pieces of codes and threw it all together.

My code looks like this:

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

public class MyClass {  
    public static void main(String args[]) {  
        Scanner keyboard = new Scanner(System.in);  
        System.out.println("press any key to exit.");  
        keyboard.next();
        System.exit(0);
    }  
    public void mouseClicked(MouseEvent evt) {  
        try {  
            Robot robot = new Robot();  
            // Simulate a key press  
            robot.keyPress(KeyEvent.VK_CONTROL);  
            robot.keyPress(KeyEvent.VK_S);  
            robot.keyRelease(KeyEvent.VK_S);   
            robot.keyRelease(KeyEvent.VK_CONTROL);  
    } catch (AWTException e) {        
        }  
    }  
}  

Solution

  • Your program has no GUI and, therefore, nothing to invoke your mouse listener. The code within the listener appears correct, all you need to do is search for how to create a basic GUI and add the mouse listener to it so you get the results you want.