Confusion between mouseEntered() and mouseMoved() - java

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class MouseEvents extends Applet implements MouseListener, MouseMotionListener
{
String msg = ""; // I am not implementing those methods which
int mouseX = 0, mouseY = 0; // are not related to my question
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseEntered(MouseEvent me)
{
mouseX = 0;
mouseY = 10;
msg = "Mouse Entered";
repaint();
}
public void mouseMoved(MouseEvent me)
{
mouseX = me.getX();
mouseY = me.getY();
showStatus("Moving mouse at "+mouseX+", "+mouseY);
}
public void paint(Graphics g)
{
g.drawString(msg, mouseX, mouseY);
}
}
Coordinates of my applet window:
Upper left corner - (0, 0)
Lower left corner - (0, 199)
Upper right corner - (349, 0)
Lower right corner - (349, 199)
What I expect:
When mouse enter the applet window, a message "Mouse Entered" should be displayed at the coordinates (0, 10)
When the mouse is moving, a message "Moving mouse at mouseX, mouseY" should be displayed in the status window. Where mouseX and mouseY are the current coordinates of the mouse
What is actually happening:
The message "Mouse entered" is not being displayed at the coordinates (0, 10), instead it is getting displayed at the initial coordinates from where the mouse enteres the applet window***
For example, the mouse enters the applet window from between Lower left corner and Lower right corner, say (187, 199), then the message "Mouse Entered", instead of getting displayed at (0, 10), is getting displayed at (187, 199)
My question
In spite of specifying mouseX = 0 and mouseY = 10 in mouseEntered(), why is the message "Mouse Entered" is getting displayed at the coordinates from where the mouse enters the applet window, but not at the coordinates (0, 10)?

The viewing pane gets redrawn very often as you move the mouse over it.
You are overwriting the values of mouseX and mouseY here:
public void mouseMoved(MouseEvent me)
{
mouseX = me.getX();
mouseY = me.getY();
showStatus("Moving mouse at "+mouseX+", "+mouseY);
}
This causes the redrawing to occur at those coordinates when you move the mouse. If you want mouseEntered to not move, you can use a local variable, e.g.
public void mouseMoved(MouseEvent me)
{
int currentMouseX = me.getX();
int currentMouseY = me.getY();
showStatus("Moving mouse at "+currentMouseX+", "+currentMouseY);
}

public void mouseMoved(MouseEvent me)
{
mouseX = me.getX();
mouseY = me.getY();
showStatus("Moving mouse at "+mouseX+", "+mouseY);
}
Your code in the mouseMoved section is being updated whenever you move the mouse. So, the reason it is displaying mouseX and mouseY not as (0,10) is because you changed the value of mouseX and mouseY in your mouseMoved method. Causing it to display coordinates at the last position of the mouse. Try creating a different variable to keep track of the position of the mouse.

Related

How can i make sure that the center of the circle remains static in processing?

I am working on this project using Unfolding-Maps library and Processing Library. I came across a code which draws a circle whose diameter increases with time and finally fades away. But the problem I face is that the center of the circle moves with my x and y coordinates of my mouse but I want it to be static not move according to my mouse movement, i.e. where I click the mouse I want the center of the circle to be that coordinate and static.
My code is as below:
boolean bCircleShow=false;
float opacity;
int diameter=0;
//
void setup () {
size (400, 300);
background (255);
smooth ();
opacity=255;
}
//
void draw() {
background (122);
//stroke (0, 255, 0);
noStroke();
fill(255);
if (bCircleShow) {
fill(255, 2, 2, opacity);
ellipse (mouseX, mouseY, diameter, diameter );
diameter ++;
opacity--;
if (opacity<=0) {
bCircleShow=false; // end
opacity=255;
diameter=0;
}
}
}
//
void mouseClicked() {
bCircleShow=true;
}
Any suggestion would be appreciated.
When you clicked on the screen store the mouse X and mouse Y of that click and then draw the circle at that mouse x and mouse y. Dont use mouseX and mouseY as they are predefined variables in processing.
Sample code.
boolean bCircleShow=false;
int mx;
int my;
float opacity;
int diameter=0;
//
void setup () {
size (400, 300);
background (255);
smooth ();
opacity=255;
}
//
void draw() {
background (122);
//stroke (0, 255, 0);
noStroke();
fill(255);
if (bCircleShow) {
fill(255, 2, 2, opacity);
ellipse (mx, my, diameter, diameter );
diameter ++;
opacity--;
if (opacity<=0) {
bCircleShow=false; // end
opacity=255;
diameter=0;
}
}
}
//
void mouseClicked() {
bCircleShow=true;
mx=mouseX;
my=mouseY;
}

Mouse Drag To Zoom implementation Java - not on click

I have written some code to implement a drag to zoom (i.e. draw a rectangle with the mouse and then zoom into this area so it fills the container) on a JPanel. However, before I wrote this into the Listener, I had a "mouseClicked" method, which is still there. This method performed a different function, simply returning the coords of the click.
Unfortunately, I mistakenly implemented the zoom function using MousePressed, which thus runs at the same time as the mouseClicked event. This means that when I click the mouse to get the coordinates, it also zooms in on a very small rectangle. Is there anyway to change this?
Thanks in advance for any suggestions, and please let me know if you need anything clarifying!
Here is the listener class:
class panelClickListener extends MouseAdapter implements MouseMotionListener {
JLabel toShowCoords, rangeLabel;
juliaPanel panelJulia;
mandPanel panelMand;
int startX, startY, currentX, currentY;
boolean dragging;
ComplexNumber startRange, endRange;
public panelClickListener(JLabel toShowCoordsIn, juliaPanel panelJuliaIn, mandPanel panelMandIn, JLabel rangeLabelIn) {
toShowCoords = toShowCoordsIn;
panelJulia = panelJuliaIn;
panelMand = panelMandIn;
rangeLabel = rangeLabelIn;
}
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
userSelectedPoint = pointsToDrawOn[x][y];
toShowCoords.setText("Number Selected: " + userSelectedPoint.getReal() + " , " + userSelectedPoint.getImaginary());
panelJulia.setFixedNumber(pointsToDrawOn[x][y]);
panelJulia.repaint();
}
public void mousePressed(MouseEvent event) {
Point point = event.getPoint();
startX = point.x;
startY = point.y;
dragging = true;
}
public void mouseReleased(MouseEvent event) {
dragging = false;
startRange = pointsToDrawOn[startX][startY];
endRange = pointsToDrawOn[currentX][currentY];
maxVal = endRange;
minVal = startRange;
rangeLabel.setText("Real axis: " + minVal.getReal() + "," + maxVal.getReal() + " - Imaginary axis: " + minVal.getImaginary() + "," + maxVal.getImaginary());
populatePointArray();
panelMand.repaint();
}
public void mouseDragged(MouseEvent event) {
Point p = event.getPoint();
currentX = p.x;
currentY = p.y;
}
}
dragging should only be set to true when mouseDragged is called, then when mouseReleased is called, you need to check to see if dragging is true before processing the zoom
There's some theory to go with that, mouseClicked will only be called if the point of the mouse is the same for mousePressed and mouseReleased.
So in a click operation you can expect mousePressed, mouseReleased and mouseClicked to be called (I believe in that order, but you'd better test it).
In a drag operation, you can expect mousePressed, mouseDragged and mouseReleased to be called

Gap between mouse on screen and JPanel on Dragndrop

I use JPanel to draw a square on the screen.
When I use MouseDragged it works fine and goes wherever I want, almost. Each time I click on the square, the square automatically moves and the top left corner goes right under the mouse.
How should I do so that the square doesn't replace itself and stays right under the mouse ?
Thanks for any help.
Keep an account of the difference between top-left coordinates of Component which you are
moving and mousePressed location.
And when you get new position, just subtract that difference to it.
Here I have tried to explain it through coding. Let myJPanel be the component you want to
move. Then here is the MouseAdapter that can work for you. New position is stored in
newPosition variable.
new MouseAdapter(){
int diffx = 0, diffy = 0;
public void mousePressed(MouseEvent e) {
Point topLeft = myJPanel.getLocation();
Point mouseDn = e.getPoint();
diffx = mouseDn.x - topLeft.x;
diffy = mouseDn.y - topLeft.y;
}
public void mouseDragged(MouseEvent e) {
Point mouseDr = e.getPoint();
int newX = mouseDr.x - diffx;
int newY = mouseDr.y - diffy;
Point newPosition = new Point(newX, newY);
}
};

JFrame Simple Application

I am working on creating a game for fun that basically is a simplistic representation for evolution.
Essentially, when I click on my moving ball it changes color. The goal is to continuously change until it matches the background color meaning the ball is successfully hidden. Eventually I will add more balls but I am trying to figure out how to change its color upon a mouse click. I have created the moving ball animation so far.
How can I change the ball color when I click on the ball?
Code:
public class EvolutionColor
{
public static void main( String args[] )
{
JFrame frame = new JFrame( "Bouncing Ball" );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
BallPanel bp = new BallPanel();
frame.add( bp );
frame.setSize( 1800, 1100 ); // set frame size
frame.setVisible( true ); // display frame
bp.setBackground(Color.YELLOW);
} // end main
}
class BallPanel extends JPanel implements ActionListener
{
private int delay = 10;
protected Timer timer;
private int x = 0; // x position
private int y = 0; // y position
private int radius = 15; // ball radius
private int dx = 2; // increment amount (x coord)
private int dy = 2; // increment amount (y coord)
public BallPanel()
{
timer = new Timer(delay, this);
timer.start(); // start the timer
}
public void actionPerformed(ActionEvent e)
// will run when the timer fires
{
repaint();
}
public void mouseClicked(MouseEvent arg0)
{
System.out.println("here was a click ! ");
}
// draw rectangles and arcs
public void paintComponent( Graphics g )
{
super.paintComponent( g ); // call superclass's paintComponent
g.setColor(Color.red);
// check for boundaries
if (x < radius) dx = Math.abs(dx);
if (x > getWidth() - radius) dx = -Math.abs(dx);
if (y < radius) dy = Math.abs(dy);
if (y > getHeight() - radius) dy = -Math.abs(dy);
// adjust ball position
x += dx;
y += dy;
g.fillOval(x - radius, y - radius, radius*2, radius*2);
}
}
Take a look at How to Write a Mouse Listener.
Don't make decisions about the state of the view in the paintComponent, painting can occur for any number of reasons, many you don't control. Instead, make theses decisions within the actionPerformed method of your Timer
You may also wish to consider changing your design slightly. Rather then having the balls as JPanels, you create a virtual concept of a ball, which contains all the properties and logic it needs and use the JPanel to paint them. You could then store them in some kind of List, each time you register a mouse click you could iterate the List and check to see if any of the balls were clicked
Have look at Java Bouncing Ball for an example
Instead of hard-coding the color (g.setColor(Color.red);), why not create an attribute:
g.setColor(currentColor);
Then when you click in the circle area, change currentColor.

Getting coordinates of mouse click on grid easy java StdDraw

okay so I am trying to get the coordinates on a grid of which square a mouse was clicked on (why i casted into int) and this is giving me like the current position of the mouse,however, I want the position after a click and for nothing to happen while it hovers.
what do i need to do?
while (gameOver==false){
mouseX= (int) StdDraw.mouseX();
mouseY=(int) StdDraw.mouseY();
game.update(mouseX, mouseY);
}
now i have
public void mouseReleased(MouseEvent e){
int mouseX = e.getX();
int mouseY = e.getY();
synchronized (mouseLock) {
mousePressed = false;
}
}
public void run(){
print();
boolean gameOver=false;
int mouseX,mouseY;
StdDraw.setCanvasSize(500, 500);
StdDraw.setXscale(0, game.gettheWidth());
StdDraw.setYscale(0, game.gettheHeight());
game.update(-1,-1);
while (gameOver==false){
mouseReleased(????)
game.update(mouseX, mouseY);
}
}
still not working
None of this is making sense still,
Could someone give me an example of it getting x and y coordinates then printing them?
I want the mouseX and mouseY to the be coordinates of the mouseclick. I've looked online I don't understand any of the other questions, I assume it has something to do with mouseevent?
StdDraw implements a MouseListener. Overload the mouseReleased method to set your mouseX and mouseY variables.
To overload, your rewrite the method the way you need it to run:
int mouseX = 0;
int mouseY = 0;
public static void main(String[] args) {
//do stuff
//...
while (gameOver == false) {
//because mouseX and mouseY only change when the mouse button is released
//they will remain the same until the user clicks and releases the mouse button
game.update(mouseX, mouseY);
}
}
//mouseReleased happens whenever the user lets go of the mouse button
#Override
public void mouseReleased(MouseEvent e) {
//when the user lets go of the button, send the mouse coordinates to the variables.
mouseX = e.getX();
mouseY = e.getY();
synchronized (mouseLock) {
mousePressed = false;
}
}
So for example, mouseX and mouseY are both 0. I click the mouse at 5, 6, drag it, and release the mouse at 120, 50. mouseReleased is called and changes mouseX to 120, and mouseY to 50. Meanwhile, game.update(0,0) has been happening. That now changes into game.update(120, 50), and will remain that way until I release the mouse button again.
To print the mouse coordinates:
#Override
public void mouseReleased(MouseEvent e) {
//when the user lets go of the button, send the mouse coordinates to the variables.
System.out.println("mouse x coord = " + e.getX());
System.out.println("mouse y coord = " + e.getY());
synchronized (mouseLock) {
mousePressed = false;
}
}

Categories