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
Related
I am working on checking if the user has clicked inside of a circle on my map. I am attempting to do this by adding a ClickHandler to my canvas, taking the distance between the center of the circle and the clicked point, then checking if that distance is less than the radius of the circle (15). It doesn't appear as if my ClickHandler code is every being hit and I'm not sure why. Clicking the map will not result in any print statements. Breakpoints inside of the ClickHandler definition will not be hit (however other breakpoints inside of getMapEvent() will be hit). All help is appreciated.
private void getMapEvent(int day) {
blinkCanvas.getCanvas().addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
System.out.println("method hit");
int screenX = event.getScreenX();
int screenY = event.getScreenY();
for (MapEvent blink : monthlyBlinks) {
Point blinkPoint = blinkToScreenXY.get(blink);
double x = blinkPoint.getX();
double y = blinkPoint.getY();
if (Math.sqrt(Math.pow(x - screenX, 2) + Math.pow(y - screenY, 2)) <= 15) {
System.out.println(" IN A CIRCLE");
}
}
}
});
}
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);
}
};
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;
}
}
I'm trying to get the mouse's position within a panel, as in the top left of the panel = x/y 0,0.
What I have at the minute gives the position on the entire screen, so depending on where the panel (which is in a frame) is on the screen, the coordinates are different. I guess you could add to the x/y co-ordinates to account for this, but this seems like a messy solution. Can anyone help?
Here's the mouseListener I'm using, which has been added to the panel.
private class MouseListener extends MouseAdapter
{
public void mouseClicked(MouseEvent e)
{
// Finds the location of the mouse
PointerInfo a = MouseInfo.getPointerInfo();
Point b = a.getLocation();
// Gets the x -> and y co-ordinates
int x = (int) b.getX();
int y = (int) b.getY();
System.out.println("Mouse x: " + x);
System.out.println("Mouse y: " + y);
// Determines which tile the click occured on
int xTile = x/tileSize;
int yTile = y/tileSize;
System.out.println("X Tile: " + xTile);
System.out.println("Y Tile: " + yTile);
}
}
See MouseEvent.getPoint().
Returns the x,y position of the event relative to the source component.
You can use MouseEvent.getX() and MouseEvent.getY() to get the relative co-ordinates of X & Y respectively.
int relativeX = e.getX();
int relativeY = e.getY();
...
I am trying to have a circle appear on the screen, then when the user clicks INSIDE the circle, enable the ability for them to drag the circle where the mouse goes while it is being pressed.
This is the code i have so far, the drag works, but it is allowing the user to drag without them pressing the inside of the circle, just when anywhere on the screen is pressed.
I hope i am not too confusing
here's the code i have, please if someone could just tell me the code that needs to be corrected, it will save me anymore hours.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DragCircle extends JFrame {
private static final long serialVersionUID = 1L;
public static int size = 400;
public static int r = 10;
private int x;
private int y;
private int cX;
private int cY;
private int dX;
private int dY;
private MouseHandler mh;
boolean isCircleClicked = false;
public static void main(String[] args) {
DragCircle c1 = new DragCircle();
c1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public DragCircle() {
super("Drag circle");
cX = r + 100;
cY = r + 100;
mh = new MouseHandler();
addMouseListener(mh);
addMouseMotionListener(mh);
setSize(size, size);
setVisible(true);
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.RED);
g.fillOval(cX, cY, r * 2, r * 2);
}
private class MouseHandler extends MouseAdapter implements
MouseMotionListener {
public void mousePressed(MouseEvent me)
{
if ((cX - me.getX()) * (cX - me.getX()) + (cY - me.getY())
* (cY - me.getY()) < r * r) {
isCircleClicked = true;
}
}
public void mouseDragged(MouseEvent me) {
if (isCircleClicked) {
x = me.getX() - dX;
y = me.getY() - dY;
cX = x + r;
cY = y + r;
repaint();
}
}
public void mouseReleased(MouseEvent e) {
isCircleClicked = false;
}
}
}
Your one problem is with
public void mouseDragged(MouseEvent me) {
if (isCircleClicked = true) {
What you're doing here is setting isCircleClicked to true every time you drag the mouse. Also this statement evaluates to true which is why you can drag anywhere and move the circle. Change this to
if (isCircleClicked) {
and you should be fine here.
The next problem is that you never reset isCircleClicked to false. You should be doing this either in mouseReleased or change your mousePressed as follows:
public void mousePressed(MouseEvent me) {
isCircleClicked =
(cX - me.getX()) * (cX - me.getX()) +
(cY - me.getY)) * (cY - me.getY()) < r * r;
}
which will set isCircleClicked accordingly.
There is still something to do, though. In the current form you need to start dragging to the upper-left of the center point, as illustrated below:
+------+
| |
| .-|-.
| / | \
+------+ |
\ /
'-_-'
This is because of your drawing: fillOval takes an upper-left corner of the oval and a width and height of the bounding rectangle. It's not the center point and the respective diameters. Hence you need to adapt his as follows:
g.fillOval(cX - r, cY - r, r * 2, r * 2);
Note the offset by the radius to the left and top.
Furthermore, your dragging code needs a bit more work. You are currently assuming that the user drags the circle's center. What you need to do is save the coordinates of the mouse click and then move the circle based on the mouse's movement relative to the last point. Currently you're moving relative to the circle's center so for the movement to be nice you have to start dragging exactly in the center of the circle. I'll leave that as an exercise for you :-)
Besides, your listener class already inherits from MouseAdapter so you don't need to explicitly implement the MouseMotionListener since MouseAdapter implements it already.
The structure of you program is wrong. You should never override the paint(...) method of a JFrame. That is an old AWT trick and should NOT be used with Swing.
Read the section from the Swing tutorial on Custom Painting for an example of the proper way to do painting. The basics are to override the paintComponent(...) method of a JPanel and then add the panel to the content pane of the frame.
With regards to you question a better solution is to create an Elllipse2D object to represent your circle. Then the custom painting can use the drawShape(...) method of the Graphics2D class. Then in you MouseListener code you can use the Shape.contains(...) method to see if the mouse was clicked on the circle.