Hi, I'm trying to display mouse coordinates (math coordinates) in my JPanel , but i get each coordinates on top of the other ,can' figure out why . here's my code :
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.applet.*;
import javax.swing.JPanel;
import javax.swing.event.MouseInputAdapter;
public class drawarea extends JPanel {
int n;
private Point mouseCoords = null;
int UNIT = 20;
drawarea() {
super();
setBackground(Color.white);
addMouseMotionListener(new MouseInputAdapter() {
public void mouseMoved(MouseEvent e) {
super.mouseMoved(e);
mouseCoords = new Point(e.getX(), e.getY());
repaint();
}
/**
* @see java.awt.event.MouseListener#mouseExited(MouseEvent)
*/
public void mouseExited(MouseEvent e) {
super.mouseExited(e);
mouseCoords = null;
repaint();
}
});
setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
}
public void paint(Graphics g) {
//draw axis x and y
g.setColor(Color.red);
g.drawLine(0, r.height / 2, r.width, r.height / 2);
g.drawLine(r.width / 2, 0, r.width / 2, r.height);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
dessinBoule(g2);
}
private void dessinBoule(Graphics2D g) {
// if mouse isnt inside the ara where
// i want the coordinates to bes displayed
if (mouseCoords == null) {
return;
}
g.setColor(Color.BLACK);
int decPolice = 15;
g.drawString("x = " + getFormatedString("" + mouseCoords.x)
+ " , y = " + getFormatedString("" + mouseCoords.y), 2, 15);
}
private String getFormatedString(String s) {
if (s.length() > 4) {
return s.substring(0, 3);
}
return s;
}
}
thanks.