JAVA坐标输入的问题,在java屏幕上显示鼠标坐标的问题

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.

解决方案

You're drawing on your graphics area, so g.drawString(...) draws a string on top of what is already there. You must either erase what is there first, by drawing a rectangle in the background colour, or use a separate component that you can manage with a separate paint(...) method.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值