我已经写了一些代码,每次移动光标时都会在光标上绘制一个圆圈,而不重新绘制Panel的所有组件,但我真的不喜欢我的解决方案而且我想知道是否有更好的解决方案可以做那。 这是我的代码:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Point2D;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class PnlMyPaintArea extends JPanel implements MouseMotionListener{
Point2D mousePos = null; //position of the cursor at the current moving
Point2D lastPos = null; //position of the cursor at the last moving
boolean state;
int width = 30, height = 30; //size of my circle
public PnlMyPaintArea() {
this.addMouseMotionListener(this);
state = false;
}
public void drawCircle() {
Graphics g = getGraphics();
g.fillOval((int)(mousePos.getX()-width/2), (int)(mousePos.getY()-height/2), width, height);
}
//this method cancels the last circle drawn in the last moving
public void coverCircle() {
Graphics g = getGraphics();
g.clearRect((int)(lastPos.getX()-width/2), (int)(lastPos.getY()-height/2), width, height);
}
@Override
public void mouseDragged(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseMoved(MouseEvent e) {
mousePos = e.getPoint();
if(state == true) { //from the second moving on I cancel the old circle and draw the new one
coverCircle();
drawCircle();
}
else if(state == false) { //at the first moving I only draw the circle
drawCircle();
state = true;
}
lastPos = mousePos;
}
}