So I’m using a pretty standard JPanel design for my game. I’m trying to test out using mouselisteners, but the getX() and getY() methods both seem to return inaccurate coordinates. When I draw a test string out on the screen at say, (100,100), and then click the on the area around the string, the getX and getY is returning values almost 100 pixels larger than what it should be. Does anyone know what I’m doing wrong exactly? I’ll post some code.
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.event.*;
import javax.swing.JPanel;
import managers.Keys;
import managers.Mouse;
public class Game extends JPanel
implements Runnable, KeyListener, MouseListener{
// dimensions
public static final int WIDTH = 480;
public static final int HEIGHT = 320;
public static final int SCALE = 2;
// game thread
private Thread thread;
private boolean running;
private int FPS = 60;
private long targetTime = 1000 / FPS;
// image
private BufferedImage image;
private Graphics2D g;
public Game() {
super();
setPreferredSize(
new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
setFocusable(true);
requestFocus();
}
public void addNotify() {
super.addNotify();
if(thread == null) {
thread = new Thread(this);
addKeyListener(this);
addMouseListener(this);
thread.start();
}
}
private void init() {
image = new BufferedImage(
WIDTH, HEIGHT,
BufferedImage.TYPE_INT_RGB
);
g = (Graphics2D) image.getGraphics();
running = true;
}
public void run() {
init();
long start;
long elapsed;
long wait;
// game loop
while(running) {
start = System.nanoTime();
update();
draw();
drawToScreen();
elapsed = System.nanoTime() - start;
wait = targetTime - elapsed / 1000000;
if(wait < 0) wait = 5;
try {
Thread.sleep(wait);
}
catch(Exception e) {
e.printStackTrace();
}
}
}
private void update() {
Keys.update();
}
private void draw() {
gsm.draw(g);
g.drawString("point",100,100);
}
private void drawToScreen() {
Graphics g2 = getGraphics();
g2.drawImage(image, 0, 0,
WIDTH * SCALE, HEIGHT * SCALE,
null);
g2.dispose();
}
public void keyTyped(KeyEvent key) {}
public void keyPressed(KeyEvent key) {
if(key.isControlDown()) {
}
Keys.keySet(key.getKeyCode(), true);
}
public void keyReleased(KeyEvent key) {
Keys.keySet(key.getKeyCode(), false);
}
public void mouseClicked(MouseEvent e) {
//System.out.print(e.getX());
}
public void mouseEntered(MouseEvent arg0) {
}
public void mouseExited(MouseEvent arg0) {
}
public void mousePressed(MouseEvent e) {
System.out.println(e.getX());
}
public void mouseReleased(MouseEvent arg0) {
}
}