1

As you can see I added the a mouse listener to the game.

import java.awt.Graphics;
import java.awt.image.BufferStrategy;

public class Game implements Runnable
{
private Display display;
public int width, height;
public String title;

private boolean running = false;
private Thread thread;

private BufferStrategy bs;
private Graphics g;

// States
public static State gameState;

// Input
private InputManager inputManager;
private MouseHandler mouseHandler;

public Game(String title, int width, int height)
{
    this.width = width;
    this.height = height;
    this.title = title;
    inputManager = new InputManager();
    mouseHandler = new MouseHandler();
}

/**
 * Initializes all of the graphics
 */
private void initialize()
{
    display = new Display(title, width, height);
    display.getFrame().addKeyListener(inputManager);
    display.getFrame().addMouseListener(mouseHandler);
    Assets.loadAssets();

    gameState = new GameState(this, 1);
    State.setState(gameState);
}

/**
 * Updates everything in the game loop
 */
private void update()
{
    if (State.getState() != null)
        State.getState().update();
}

private void render()
{
    bs = display.getCanvas().getBufferStrategy();

    // If this is the first time running initialize the buffer strategy
    if (bs == null)
    {
        display.getCanvas().createBufferStrategy(3);
        return;
    }

    g = bs.getDrawGraphics();
    // Clear the screen
    g.clearRect(0, 0, width, height);

    // Drawing
    if (State.getState() != null)
        State.getState().render(g);
    // End drawing
    bs.show();
    g.dispose();
}

public void run()
{

    initialize();

    // Updates the game loop 60 times every 1 second = 1,000,000,000
    // nanoseconds
    int fps = 60;
    double timePerUpdate = 1000000000 / fps;
    double timeElapsed = 0;
    long now;
    // Current time of computer in nanoseconds
    long lastTime = System.nanoTime();

    // Game loop
    while (running)
    {
        now = System.nanoTime();
        timeElapsed += (now - lastTime) / timePerUpdate;
        lastTime = now;

        if (timeElapsed >= 1)
        {
            update();
            render();
            timeElapsed--;
        }
    }

    stop();
}

public synchronized void start()
{
    // Do not make a new thread if it is already running
    if (running)
        return;

    // Starts the game
    running = true;
    thread = new Thread(this); // this = Game class
    thread.start(); // Goes to run
}

public synchronized void stop()
{
    // In case stop gets called and it is already not running
    if (!running)
        return;

    // Stops the game
    running = false;
    try
    {
        thread.join();
    }
    catch (InterruptedException e)
    {
        e.printStackTrace();
    }
}

public InputManager getInputManager()
{
    return inputManager;
}

public MouseHandler getMouseHandler()
{
    return mouseHandler;
}

public static void main(String[] args)
{
    Game game = new Game("Game", 1024, 768);
    game.start();
}
}

This is my mouse adapter class, basically all I want is the x,y coordinates of where the mouse is pressed

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class MouseHandler extends MouseAdapter
{
public int x, y;

public MouseHandler()
{

}

public void MousePressed(MouseEvent e)
{
    x = e.getX();
    y = e.getY();
}
}

When I try to get the X, and Y coordinates they are always 0 instead of where the mouse actually clicked. I have no clue why.

noobycoder
  • 63
  • 2
  • 13
  • `display.getFrame()`? – MadProgrammer Jun 10 '15 at 04:23
  • There are lots of posts on here about that. Please search before posting a question that has been answered. http://stackoverflow.com/questions/12396066/how-to-get-location-of-a-mouse-click-relative-to-a-swing-window http://stackoverflow.com/questions/1439022/get-mouse-position http://stackoverflow.com/questions/5125853/how-to-get-mouse-position-of-a-java-application http://javalessons.com/cgi-bin/fun/java-programming.cgi?1cd=mev – M H Jun 10 '15 at 04:24
  • @MadProgrammer I have a separate method for making the frame. [pastebin](http://pastebin.com/SM4bcXar). – noobycoder Jun 10 '15 at 04:44
  • @Hanoncs I did search for my question, and watched a couple of youtube tutorials. I think i'm adding it the right way, but it still doesn't work. (even after I fixed the case) – noobycoder Jun 10 '15 at 04:49

1 Answers1

2
public int x, y;

int variables are always initialized to 0.

public void MousePressed(MouseEvent e)

Method names are case sensitive.

Your code is never executed since the method to override should be mousePressed(...). Fix the typo in your code.

Always use code like:

@Override
public void mousePressed(MouseEvent e)

Then if you make a typo the compiler will tell you.

When I try to get the X, and Y coordinates they are always 0

Since your code is never executed the default value is returned.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • Still doesn't work :( I can't believe I didn't realise that. I just fixed the case. It actually never registers any clicks, before i was getting the x and y in another class. – noobycoder Jun 10 '15 at 04:37
  • I fixed the case, but it seems like the mouse clicks are never registering, before I was getting the x and y in another method – noobycoder Jun 10 '15 at 04:47
  • @noobycoder You're adding the `MouseListener` directly to the frame, which has a `JRootPane`/contentPane (and in your case a) `Canvas` ontop of it, one of these (I'm betting the `Canvas`) is consume the `MouseEvents` before they reach the frame. You REALLY want to add the `MouseListener` to the `Canvas`, as `MosueEvent`s are contextual to the component the generated them, if you were able to use the frame, the coordinates would be offset set by some weird amount because of the frame decorations – MadProgrammer Jun 10 '15 at 06:14
  • If you're satisfied with my reasoning of the previous comment, then you could update your answer and that should cover just about all the issues, related to the `MouseListener` ;) (I was able to hobble together a runnable example from the posted and linked codes, replicated and fix the issues as described in your answer and my comments) – MadProgrammer Jun 10 '15 at 06:16
  • @MadProgrammer how do i give you rep, I added a mouse listener to my canvas and now it works, thanks man – noobycoder Jun 10 '15 at 06:35
  • You don't, but camickr gave you most of the fixes, that was just the link the chain ;) – MadProgrammer Jun 10 '15 at 06:41