How to find direction of swipe in jframe - java

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!

Related

Keyboard input trigger mouse click

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.

Java - Freeze Mouse

Is there a way to lock the mouse in one position in Java for a certain amount of time?
I've tried this:
while(timer == true){
Robot bot = new Robot();
bot.mouseMove(x, y);
}
But when the user moves the mouse it jumps unpleasantly back and forth (from the position the user is dragging to the position where it's supposed to be locked).
Any ideas if there is a better way to do this? Or can I completely disable user input for the mouse? Thanks in advance!
This is as far as you can go (at least with the standard libraries). The mouse "jumps" are system dependent, specifically on the "sampling rate" of the listener. I'm not aware of a JVM parameter affecting it, but wouldn't be surprised if there is something in that spirit. The jumps are in opposite relation to the mouse acceleration (the mouse can move a "long" distance between the samples).
public class Stop extends JFrame {
static Robot robot = null;
static Rectangle bounds = new Rectangle(300, 300, 300, 300);
static int lastX = 450; static int lastY = 450;
Stop() {
try {
robot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
addMouseMotionListener(new MouseStop());
getContentPane().add(new JLabel("<html>A sticky situation<br>Hold SHIFT to get out of it", JLabel.CENTER));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setBounds(bounds);
setVisible(true);
}
private static class MouseStop extends MouseAdapter {
#Override
public void mouseMoved(MouseEvent e) {
if(e.isShiftDown()) {
lastX = e.getXOnScreen();
lastY = e.getYOnScreen();
}
else
robot.mouseMove(lastX, lastY);
}
}
public static void main(String args[]) {
new Stop();
}
}
Edit: I have just gotten an idea involving painting of the cursor to appear as if the mouse is not moving at all. I'll add code if I get something working.

Capturing mouse movement while moused pressed in Java

I'm trying to get the mouse position while pressing the mouse button but it doesn't work.
I'm extending the MouseAdapter and as stated at the Javadoc the mouseMove() is invoked when the mouse cursor has been moved onto a component but no buttons have been pushed.
This is an example class I have created to show you my problem:
public class TestMouse extends MouseAdapter{
int x,y;
boolean pressed;
public void mousePressed(MouseEvent e){
pressed = true;
}
public void mouseReleased(MouseEvent e){
pressed = false;
}
/*
Invoked when the mouse is not pressed only.
*/
public void mouseMoved(MouseEvent e){
x = e.getX();
y = e.getY();
}
/*
I want something like that.
*/
public void mousePressedAndMoved(MouseEvent e){
....
}
}
That's the problem with MouseAdapter, since it's a abstract class and not an interface (MouseMotionListener is the one you need), it gives empty implementations for all the possible events just to avoid you from being forced to override them all, this also implies that you could miss some of these events if you don't read docs.
If you look carefully at documentation though, you will see that you have
public void mouseDragged(MouseEvent e)
that you can override to listen exactly to what you need.

mouse listener on frame

Hi
i am trying to add a mouse listener to my frame to get the position of the mouse clicked and check if it is inside the circle, the problem is that it is not triggering
public class CircleDraw extends Frame implements MouseListener {
static int circles = 0;
private double color;
double mousex = 0;
double mousey = 0;
int score;
public void mouseClicked(MouseEvent evt)
{
mousex = evt.getX();
mousey = evt.getY();
}
public void mouseEntered (MouseEvent me) {}
public void mousePressed (MouseEvent me) {}
public void mouseReleased (MouseEvent me) {}
public void mouseExited (MouseEvent me) {}
public void paint(Graphics g) {
try {
this.addMouseListener(this);
while (circles < 20) {
color = 10*Math.random();
Shape circle = new Ellipse2D.Double(900*Math.random(),900*Math.random(), 50.0f, 50.0f);
Graphics2D ga = (Graphics2D)g;
ga.draw(circle);
if(color >2)
ga.setPaint(Color.green);
else
ga.setPaint(Color.BLACK);
ga.fill(circle);
if(circle.contains(mousex, mousey) && color > 2)
score ++;
else
if(circle.contains(mousex, mousey) && color < 2)
score--;
Thread.sleep(1000);
System.out.println(circles);
System.out.println(mousex);
System.out.println(mousey);
circles ++;
ga.setPaint(Color.white);
ga.fill(circle);
}
System.exit(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
Frame frame = new CircleDraw();
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
frame.setSize(1000, 1000);
frame.setVisible(true);
}}
It is deadly to add your mouselistener in the paint() method, since this method is called very very often (with each repaint), and so many listeners are added (with each repaint).
You should add the listener to your content-panel and not to the JFrame itself. This will do it. You can do this in the constructor of your class:
public CircleDraw() {
this.getContentPane().addMouseListener(this);
}
This won't solve your problem completely I think, since you won't get your mouseclick while your paint-method is active. Your code-design (especially your while-loop) does not give any time to other events to fire. So the mouseclick-event will be handled after your 20 loops. You can check this by adding
public void mouseClicked(MouseEvent evt) {
mousex = evt.getX();
mousey = evt.getY();
System.out.println("X: "+mousex+"/ Y: "+mousey);
}
to your code. You have to run your GUI in a different thread (e.g. use SwingUtilities and a Runnable() therefor). I recommend you to get a good book on JAVA development. Or you can start with online-tutorials like this one.
IMHO you should not try to deal with awt, instead use SWING or SWT for GUI-design, since this is much more compfortable.
add the listener in the constructor, the paint is called repeatedly
Here are some of the problems I see with that source:
Adds the listener in paint()
Calls wait() within the paint() method.
Calls System.exit() within the paint() method (not strictly a problem, but very unusual).
Is poorly formatted and hard to understand
Calls deprecated methods.
Codes in AWT in the wrong millennium.

Dragging JPanel

I've got a problem when trying to drag a JPanel. If I implement it purely in MouseDragged as:
public void mouseDragged(MouseEvent me) {
me.getSource().setLocation(me.getX(), me.getY());
}
I get a weird effect of the moved object bouncing between two positions all the time (generating more "dragged" events). If I do it in the way described in this post, but with:
public void mouseDragged(MouseEvent me) {
if (draggedElement == null)
return;
me.translatePoint(this.draggedXAdjust, this.draggedYAdjust);
draggedElement.setLocation(me.getX(), me.getY());
}
I get an effect of the element bouncing a lot less, but it's still visible and the element moves only ½ of the way the mouse pointer does. Why does this happen / how can I fix this situation?
OK. Old question but if anyone comes across this like I did this can be solved relatively simply. For dragging a JPanel in a JFrame I did:
#Override
public void mousePressed(MouseEvent e) {
if (panel.contains(e.getPoint())) {
dX = e.getLocationOnScreen().x - panel.getX();
dY = e.getLocationOnScreen().y - panel.getY();
panel.setDraggable(true);
}
}
#Override
public void mouseDragged(MouseEvent e) {
if (panel.isDraggable()) {
panel.setLocation(e.getLocationOnScreen().x - dX, e.getLocationOnScreen().y - dY);
dX = e.getLocationOnScreen().x - panel.getX();
dY = e.getLocationOnScreen().y - panel.getY();
}
}
The key is to use .getLocationOnScreen() and update the adjustment at the end of each call of mouseDragged.
Try this
final Component t = e.getComponent();
e.translatePoint(getLocation().x + t.getLocation().x - px, getLocation().y + t.getLocation().y - py);
and add this method:
#Override
public void mousePressed(final MouseEvent e) {
e.translatePoint(e.getComponent().getLocation().x, e.getComponent().getLocation().y);
px = e.getX();
py = e.getY();
}
I don't know if you can just do it using a mouseDragged event. In the past I use mousePressed to save the original point and mouse dragged to get the current point. In both cases I translate the points to the location on the screen. Then the difference between the two points is easily calculated and the location can be set appropriately.
My general purpose class for this is the Component Mover class.

Categories

Resources