Keyboard input trigger mouse click - java

I want to create a program / script which triggers mouse clicks or drag an drops when the keyboard is used. For example: If u press 1, the mouse location is saved. If u press 2 the mouse will go to the saved location. I know this is possible in different programming languages and i was wondering which one is the best to use for this purpose. And could someone give me a little headstart?
Edit:
import java.awt.MouseInfo;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import java.awt.AWTException;
import java.awt.event.*;
public class nudan implements KeyListener{
int x1;
int y1;
public static void main(String[] args) throws AWTException{
JFrame jf = new JFrame("Key Event");
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.addKeyListener(new nudan());
jf.setVisible(true);
jf.setAlwaysOnTop(true);
Robot rt = new Robot();
}
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == e.VK_NUMPAD1){
System.out.println("Key Pressed: " + e.getKeyChar());
this.y1 = MouseInfo.getPointerInfo().getLocation().y;
this.x1 = MouseInfo.getPointerInfo().getLocation().x;
}
}
#Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == e.VK_NUMPAD2){
System.out.println(x1);
System.out.println(y1);
try {
new Robot().mouseMove(x1, y1);
} catch (AWTException e1) {
e1.printStackTrace();
}
}
}
#Override
public void keyTyped(KeyEvent e) {
}
}
Thank you so far guys. So this works. It saves the location and Prints '1' if you press Numpad 1. When numpad 2 is pressed, it goes to the saved location and prints the saved location. But somehow when i start my game and try to use this, my mouse doesn't move, eventhought it prints the locations so the script is still running. Anyone has a clue?

This can be done with pretty much every language in a fairly easy way, there is no need to use a specific language for it.
I assume you just started out programming, so one golden rule in programming: just Google it!
For java you can easily find the documentation of the MouseInfo class (java.awt.MouseInfo), which will in large provide the functionalities you'll need.
Java
import java.awt.MouseInfo;
public class ExampleMouseInfo {
public static void main(String[] args){
int mouseYPos = MouseInfo.getPointerInfo().getLocation().y;
int mouseXPos = MouseInfo.getPointerInfo().getLocation().x;
System.out.println(mouseXPos);
System.out.println(mouseYPos);
}
}
Output
488
477
This snippet of code will get the position of your mouse when you run the program. So if you want to trigger this part of code at a certain point (like you said by pressing a button) you make a function out of it and wrap it into an event handler.
Edit: example of moving a mouse can be found here.

Related

How to ask for a keybind within an action

I was playing around in Java and trying to make an autoclicker just as a challenge for myself. I was making key bindings to turn it on and off when I discovered that I needed to turn off a while loop from a different class. Normally I would think this to be easy but I am using actions, so the action keeps playing until it is broken. I thought about it for a little bit and came to the conclusion that I needed to ask for a keybind within an action, but I have no idea how to do this. Here is my code right now if you want to help me make some improvements
package autoclicker;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Autoclicker {
JFrame frame;
JLabel label;
boolean endis;
Action enableAction;
public Autoclicker() {
frame = new JFrame("Autoclicker");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(420, 420);
frame.setLayout(null);
label = new JLabel();
label.setBackground(Color.red);
label.setBounds(100, 100, 100, 100);
label.setOpaque(true);
enableAction = new EnableAction();
label.getInputMap().put(KeyStroke.getKeyStroke("UP"), "enableAction");
label.getActionMap().put("enableAction", enableAction);
frame.add(label);
frame.setVisible(true);
}
public class EnableAction extends AbstractAction {
#Override
public void actionPerformed(ActionEvent e) {
endis = true;
try {
Robot robot = new Robot();
while(endis) {
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
}
} catch (AWTException e1) {
e1.printStackTrace();
}
}
}
}
Assuming you want to use your autoclicker on other programs besides the java application, this isn't an easy thing to do. Java Swing was only designed to get events (such as keyboard presses) from the window that's currently focused on.
However, according to MasterID on this stack overflow post, it is possible with this library: https://github.com/kwhat/jnativehook. I haven't used this library myself though.
I've made my own auto clicker a long time ago, and here's how I dealt with exiting the loop. Mouse Position is something that is easy to get in Java. MouseInfo.getPointerInfo().getLocation(); So, rather than breaking on a keypress (requiring JFrame focus in Swing), you can break on if the mouse has been moved. In your loop, if the mouse is ever not in the same position, that means it has been moved, so exit the loop.
Perhaps something like this:
public void mainLoop() {
// Sleep for an amount of time to get mouse into proper position
Thread.sleep(4000);
...
Point p = MouseInfo.getPointerInfo().getLocation();
int lastX = (int)p.getX();
int lastY = (int)p.getY();
while(!isMoved(lastX, lastY)) {
// Do Click or other Stuff...
}
}
/** Returns true if the last x and y position don't match the current mouse x and y position on the screen. False if same position. */
public boolean isMoved(int lastX, int lastY){
Point p = MouseInfo.getPointerInfo().getLocation();
return (int)p.getX() != lastX || (int)p.getY() != lastY;
}
This breaks out of the loop if the mouse is ever moved. And if you want to use Robot.mouseMove(), you could make a simple wrapper class for Robot to handle updating the last position for you.

Gui- make an object move by a certain criteria

I am trying to make a particular "Pacman Game".
Basically the main objects are: pacman and fruit.
The background image is a picture of a certain map, meaning the game is bound by an exterior frame.
The frame itself is set in pixels which I convert to coordinates (Conversion of lat/lng coordinates to pixels on a given map (with JavaScript)).
coordinates have the following parameters:
public Point3D(double x,double y,double z)
{
_x=x;// latitude
_y=y;// longtitude
_z=z;// altitude
}
public boolean isValid_GPS_Point(Point3D p)
{
return (p.x()<=180&&p.x()>=-180&&p.y()<=90&&p.y()>=-90&&p.z()>=-450);
}
Fruits are static objects that do not move.
All pacmen have a universal speed of 1 meter per second and an eating radius of 1 meter, meaning every fruit in the eating radius of the particular pacman will be eaten and removed from fruit list(The 'Eating Radius' is more like a third dimensional sphere having a 1 meter radius).
Pacmen movement is determined by an algorithm (Algorithm: using a list of fruits and pacmen, we calculate the distance of 2 objects from both lists, taking the minimal distance needed for a specific pacman to travel.
Distance Formula:
Determining the vector by 2 GPS points on map.
Using square function on the vector: sqrt(delta(x)^2+delta(y)^2+delta(z)^2)
In terms of Gui:
package gui;
import java.awt.Graphics;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class MainWindow extends JFrame implements MouseListener
{
public BufferedImage myImage;
public MainWindow()
{
initGUI();
this.addMouseListener(this);
}
private void initGUI()
{
MenuBar menuBar = new MenuBar();
Menu File = new Menu("File");
Menu Run=new Menu("Run");
Menu Insert=new Menu("Insert");
MenuItem New=new MenuItem("New");
MenuItem Open = new MenuItem("Open");
MenuItem Save=new MenuItem("Save");
MenuItem start=new MenuItem("start");
MenuItem stop=new MenuItem("stop");
MenuItem packman=new MenuItem("packman");
MenuItem fruit=new MenuItem("fruit");
menuBar.add(File);
menuBar.add(Run);
menuBar.add(Insert);
File.add(New);
File.add(Open);
File.add(Save);
Run.add(start);
Run.add(stop);
Insert.add(packman);
Insert.add(fruit);
this.setMenuBar(menuBar);
try {
myImage = ImageIO.read(new File("C:\\Users\\Owner\\Desktop\\Matala3\\Ariel1.png"));//change according to your path
} catch (IOException e) {
e.printStackTrace();
}
}
int x = -1;
int y = -1;
public void paint(Graphics g)
{
g.drawImage(myImage, 0, 0, this);
if(x!=-1 && y!=-1)
{
int r = 10;
x = x - (r / 2);
y = y - (r / 2);
g.fillOval(x, y, r, r);
}
}
#Override
public void mouseClicked(MouseEvent arg) {
System.out.println("mouse Clicked");
System.out.println("("+ arg.getX() + "," + arg.getY() +")");
x = arg.getX();
y = arg.getY();
repaint();
}
#Override
public void mouseEntered(MouseEvent arg0) {
System.out.println("mouse entered");
}
#Override
public void mouseExited(MouseEvent arg0) {
System.out.println("mouse exited");
}
#Override
public void mousePressed(MouseEvent arg0) {
System.out.println("mouse Click pressed");
}
#Override
public void mouseReleased(MouseEvent arg0) {
System.out.println("mouse Click released");
}
}
Running it from this class:
package gui;
import javax.swing.JFrame;
import Geom.Point3D;
import gis.Fruit;
public class Main
{
public static void main(String[] args)
{
MainWindow window = new MainWindow();
window.setVisible(true);
window.setSize(window.myImage.getWidth(),window.myImage.getHeight());
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
My main goal is after that after I place my objects(pacmens and fruits) on the map it should somehow look like this: https://media.giphy.com/media/5UDHI0JLxBBElUFuCs/giphy.gif
I'm looking for a general direction for how to make my packmen move like this and not stay stationary.
You want to make so that the pac men (?) will chase the fruits in a straight line, right?
This is really simple and it should look hilarious if you add more and more features.
You would make a loop trying to find the closest fruit and then make a line using two points: the position of the pacman and the fruit. You then need to subtract the point of the fruit minus the pacman. This is the vector that represents the line the pacman will need to go. Normalize the vector to get a unit-length vector that we can work with. Now, we need to add a tiny fraction of this vector to move the pacman to the fruit. The formula is "
vector * speed * time_delta
", where time_delta is 1 divided by the fps or the actual time difference if you can get it. I normally use the first. This is so in one second, you pacman will have moved at the specified speed. (Keep in mind you specify how many meters a pixel is!)
// calculate line
Vector a = packman.getPosition();
Vector b = fruit.getPosition();
Vector ab = b.subtract(a).normalize();
// for each tick!
packman.addPosition(ab.multiply(speed * 1 / fps));
Reference:
For the eating part you only delete fruits from a list if they are close enough from the pacman. To add fruits you can do the same, add them to a list. You can also make the pacman store the fruit object to simulate a "target lock" or constantly check for the closest fruit.
Hope this has helped you and I would love to see your game!

How to find direction of swipe in jframe

I am working on a swing application which run on a touch screen linux tablet. I want to implement a module in which i find that in which direction user swipe its finger on the screen. I am using MouseMotionListener to find the position of the mouse. But confusing now that how i can find the exact direction of the mouse movement. I only interested to find upward and downward movement on jframe. Can someone give me idea about that
I am using MouseMotionListener to find the position of the mouse.
I would guess you need to keep track of two MouseEvents:
the previous event (or maybe the mousePressed event which started the swipe?)
the current event.
so that you have access to the two points generated by each event.
Then you compare the two points using basic math. If the current y value is greater you are swiping down, otherwise up.
I wanted to add this example code illustrating #camickr's answer since it might help - as it got rejected as an edit, and I don't have enough points to add comments, here it is:
import javax.swing.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class DragDirectionDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("Drag Direction Demo");
frame.setSize(500, 500);
frame.setVisible(true);
frame.addMouseListener(new MouseListener() {
float lastY = 0;
public void mouseReleased(MouseEvent e) {
System.out.println("Mouse released at " + e.getY());
if (e.getY() < lastY) {
System.out.println("Upward swipe");
} else if (e.getY() > lastY) {
System.out.println("Downward swipe");
} else {
System.out.println("No movement");
}
;
}
public void mousePressed(MouseEvent e) {
System.out.println("Mouse clicked at " + e.getY());
lastY = e.getY();
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
});
}
});
}
}
It is just a toy example illustrating the approach explained in #camickr's answer: tracking the y coordinate when the motion starts (the mouse button being depressed, in my example); then, comparing it to the y coordinate when the motion finishes (mouse button released, in my example - may need tweaking for touch, I don't know).
Observe the console output indicating what the motion has been picked up as. Good luck!

Is there a way of placing a video in my Java game main menu

I have made a simple Java game, when I load the game a start-up menu pops up with a simple play button and a close button, if I press the start button Java changes to another class which takes the user to the game, if I press close the game shuts down. At the moment the game menu is very boring I wish to add a video to the start-up menu, is this possible using Java code and if so, is it complicated?
My code so far for my menu is shown bellow, the main two methods are the render and update methods, the render tells java what to add to the screen and the update method tells java what to do if a button is pressed:
package javagame;
import org.lwjgl.input.Mouse;
import org.newdawn.slick.*;
import org.newdawn.slick.state.*;
public class Menu extends BasicGameState{
//public String mouse= "no input yet";//COORDS if needed
Image bg;
public Menu(int state){
}
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException{
bg = new Image("res/croftbg.png");
}
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException{
bg.draw(0,0);
//g.drawString(mouse, 10, 50);//COORDS if needed
}
public void update(GameContainer gc, StateBasedGame sbg, int delta)throws SlickException{
int posX = Mouse.getX();
int posY = Mouse.getY();
//mouse = "mouse pos:" +posX+" " +posY;//Coords if needed
//play now button
if((posX>110 && posX<140) && (posY>5 && posY<25)){//checks if mouse is inside play now button
if(Mouse.isButtonDown(0)){//checks if left mouse pressed
sbg.enterState(1);//change to play state ie(1)
}
}
//exit button
if((posX>510 && posX<535) && (posY>5 && posY<25)){
if(Mouse.isButtonDown(0)){
System.exit(0);//closes the widow
}
}
}
public int getID(){
return 0;
}
Also, I do not require any audio, I only need the video.
Thank you in advance.
I would suggest you taking a look at Xuggler, as I think JMF is not widely used anymore.
I would also take a look at this Stack Overflow Question/Answer as it really does answer your question quite nicely.
Of course you can, use Java Media Framework
// A JPanel the plays media from a URL
import java.awt.BorderLayout;
import java.awt.Component;
import java.io.IOException;
import java.net.URL;
import javax.media.CannotRealizeException;
import javax.media.Manager;
import javax.media.NoPlayerException;
import javax.media.Player;
import javax.swing.JPanel;
public class MediaPanel extends JPanel {
public MediaPanel(URL mediaURL) {
setLayout(new BorderLayout()); // use a BorderLayout
// Use lightweight components for Swing compatibility
Manager.setHint(Manager.LIGHTWEIGHT_RENDERER, true);
try {
// create a player to play the media specified in the URL
Player mediaPlayer = Manager.createRealizedPlayer(mediaURL);
// get the components for the video and the playback controls
Component video = mediaPlayer.getVisualComponent();
Component controls = mediaPlayer.getControlPanelComponent();
if (video != null) {
add(video, BorderLayout.CENTER); // add video component
}
if (controls != null) {
add(controls, BorderLayout.SOUTH); // add controls
}
mediaPlayer.start(); // start playing the media clip
} // end try
catch (NoPlayerException noPlayerException) {
System.err.println("No media player found");
} // end catch
catch (CannotRealizeException cannotRealizeException) {
System.err.println("Could not realize media player");
} // end catch
catch (IOException iOException) {
System.err.println("Error reading from the source");
} // end catch
} // end MediaPanel constructor
} // end class MediaPanel
REFERENCES
http://www.deitel.com/articles/java_tutorials/20060422/PlayingVideowithJMF/

Why is this java applet code not picking up every MouseClicked event?

I'm following this [slightly old tutorial for 2d java games here][1].
I have a basic applet that runs in a thread with a mouselistener.
On left button click I can shoot up to 10 claypigeons (balls) from the bottom of the window. On right button click I "shoot" and if I hit a pigeon it is removed from the screen.
I've noticed however that sometimes right clicks are not getting picked up. This is not necessarily when there is a lot going on on the screen, although never at the beginning before it all kicks off. At worst it can take 3 or 4 clicks before one is registered.
I'm guessing that I'm doing something obviously wrong in my code, but I'm not sure what. My first thought was the for loops that loop through every object every frame to recalculate their position or check if they have been "shot"? Could they been "blocking" the mouselistener?!
Any tips on how to debug this are welcome!
*********EDIT***********
Ok I've taken the very good advice given below and reduced the code to the smallest nutshell that reproduces the bug. I think I had it in my head that it was all the for loops and the complexity that were causing the problems which is why I included so much in my first code.
So as it happens I can reproduce this bug with almost no code, but at the same time it the bug is much milder. With the code below I just have the basic applet and the mouselistener and on right click a count increments in console and prints its value to screen. This works fine most of the time, but every now and again, a right click is "lost" and not registered.
With the full class, I could sometimes get sequences of 3 or 4 or more right clicks not being registered, so the bug was much more obvious. Anyway code is below, only one class this time:
Main class code:
package javacooperation;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.net.*;
public class ClayPigeonGame extends Applet implements Runnable, MouseListener {
//counters and flags for debugging
private boolean flag = true;
private int click_count = 0;
private boolean game_running;
public void init(){
//set boolean for while loop
game_running=true;
addMouseListener(this);
}
public void start() {
//threading this applet.. why?
Thread th = new Thread(this);
//does this call the run method in the class?
th.start();
}
public void stop(){
game_running=false;
}
public void destroy() { }
public void run(){
while(game_running) {
//updatePigeonPosition();
repaint();
try{
//stop thread for 20 milliseconds
Thread.sleep(20);
} catch (InterruptedException ex){ }
}
}
public void paint(Graphics g){ }
public void mouseClicked(MouseEvent e) {
switch (e.getButton()){
case MouseEvent.BUTTON1:
case MouseEvent.BUTTON2:
break;
case MouseEvent.BUTTON3:
click_count ++;
System.out.println("Right click count: " + click_count);
break;
default:
break;
}
}
//all the mouse listening events required because we implemented MouseListener
public void mouseReleased(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { }
public void mousePressed(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
}
It's possible I guess that your code is interfering with the mouse clicked detection timing as a click is actually both a press and a release with the correct bounds etc. Have you tried not using the clicked call back and instead use the pressed (move the code to mousePressed instead) ?

Categories

Resources