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;
}
}
Related
Me and my partner are attempting to create the game Pong for our computer science final project. We created a reference code where 2 cubes can be controlled upwards and downwards and it works fine. The problem occurs when attempting to control both cubes at the same time (only 1 cube will move at a time). We want to make both cubes move at the same time.
WE want to say that:
yPos - is the y position of the black cube
xPos - is the x position of the black cube
xPos2 - is the x position of the blue cube
YPos2 - is the y position of the blue cube
Keys:
A - Go up for black cube
Z - Go down for black cube
K - Go up for blue cube
M - go down for blue cube
We have tried using a more complicated version which used j-label animation. How ever we want to make our pong game through the graphics function. But we do not understand:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class PongHelpNeed extends JFrame implements KeyListener
{
// booleans to tell which key is pressed
boolean upKey;
boolean downKey;
boolean upKey2;
boolean downKey2;
// the position variables
int yPos;
int xPos;
int xPos2;
int yPos2;
public PongHelpNeed ()
{
//create window
super ("Controller");
setSize (660, 700);
// set keys to false and original positions
upKey = false;
downKey = false;
upKey2 = false;
downKey2 = false;
xPos = 100;
yPos = 350;
xPos2 = 500;
yPos2 = 350;
// add the frame as a listener to your keys
addKeyListener (this);
// Show the frame
setVisible(true);
}
//needs to be here because the class implements KeyListener
public void keyTyped (KeyEvent e)
{
System.out.println (e.getKeyCode () + " Typed");
}
//needs to be here because the class implements KeyListener
public void keyPressed (KeyEvent e) {
//check if keys a,z or k,m are pressed
if (e.getKeyCode () == KeyEvent.VK_A)
{
upKey = true;
}
else if (e.getKeyCode () == KeyEvent.VK_Z)
{
downKey = true;
}
else if (e.getKeyCode () == KeyEvent.VK_K)
{
upKey2 = true;
}
else if (e.getKeyCode () == KeyEvent.VK_M)
{
downKey2 = true;
}
//repaint the window everytime you press a key
repaint ();
}
//needs to be here because the class implements KeyListener
public void keyReleased (KeyEvent e)
{
System.out.println (e.getKeyCode () + " Released");
}
//paints the pictures
public void paint (Graphics g)
{
//set background
g.setColor(Color.WHITE);
g.fillRect(0, 0, 660, 700);
//cube 1
g.setColor(Color.BLACK);
g.fillRect(xPos,yPos,50, 50);
//draw cube 2
g.setColor(Color.BLUE);
g.fillRect(xPos2,yPos2, 50, 50);
//if keys are pressed move the cubes accordingly up or down
if (upKey == true)
{
yPos = yPos - 15;
upKey = false;
}
else if (downKey == true)
{
yPos = yPos + 15;
downKey = false;
}
else if (downKey2 == true){
yPos2 = yPos2 + 15;
downKey2 = false;
}
else if (upKey2 == true) {
yPos2 = yPos2 - 15;
upKey2 = false;
}
}
public static void main (String[] args)
{
new PongHelpNeed ();
}
}
Our expected results are we are trying to move both cube at the same time. So when we press the A key and the K key the black square should move and the blue cube should move.
Calling repaint() does not trigger a call to the paint immediately, so it's possible that the keyPressed is triggered twice (or more) before paint.
In your paint method you are checking the keys in if-else, which means that if one of the flags is true, the rest are not checked. You also have a race condition where the keyPressed is fighting with paint over the flags. Also, if you press a key quickly multiple times, you'll lose all the extra key presses between the first handled event and the next repaint.
Instead of doing the move within paint, you should do it within the keyPressed handler. Don't set a flag to e.g. upKey = true;, but instead do the action directly: yPos = yPos - 15;. The paint method will then just refresh the view to reflect the current (updated) state.
I've created a Java-Application to add/remove and show a random number of points on a JPanel. It is possible to move the points per drag&drop. To undo the last actions I buffer the points.
My question: if a point will moved via 'mouseDragged', is it possible to save the first mouseposition while the drag begins? I've tried the following:
public void mouseDragged(MouseEvent e) {
int x = e.getX();
int y = e.getY();
if (!points.isEmpty() && curPointIndex > -1) {
if (move == false) {
pointmove = new Point(x,y);
move = true;
}
}
}
The method mouseReleased change the variable move back to false. The variable pointmove should save the first point, but it changes all the time while the mouse is dragged.
Could anyone discribe why or what I can to do differently?
As Arnaud mentioned, you can use mousePressed to store the initial point:
#Override
public void mousePressed(MouseEvent e)
{
Point initialPoint = e.getPoint();
}
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
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");
}
}
}
});
}
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.