现在,我正在尝试获取它,以便每当我在绘制的椭圆内单击时,拖动鼠标,它将通过重新绘制来移动位置。但是,即使正确检测到MouseEvent,椭圆形图像也不会更新。我对为什么会感到困惑。以下是处理椭圆形,MouseEvents和更新的代码:
public class DrawOval extends JPanel {
private int size = 50;
private int locX = 0; //vector points
private int locY = 0;
private boolean isPressed = false;
private Shape oval = new Ellipse2D.Double(locX, locY, size, size * 2);
public DrawOval(int size){
this.size = size;
Dimension dims = new Dimension(size, size);
setPreferredSize(dims);
setMaximumSize(dims);
setMinimumSize(dims);
MouseAdapter m = new MouseAdapter(){
public void mouseReleased(MouseEvent e){
isPressed = false;
update(e);
System.out.println("Mouse is released!");
}
public void mousePressed(MouseEvent e){
isPressed = true;
update(e);
System.out.println("Mouse is pressed!");
}
public void mouseDragged(MouseEvent e){
if(isPressed){
update(e);
System.out.println("Mouse is dragged!");
}
}
public void update(MouseEvent e){
System.out.println("X: " + e.getX() + ", Y: " + e.getY());
if(oval.contains(e.getX(), e.getY())){
setX(e.getX()); setY(e.getY());
repaint();
}
//does not update if the mouses click coordinates are outside of the oval
}
};
addMouseListener(m); //for pressing and releasing
addMouseMotionListener(m); //for dragging
}
public void setX(int _x){
this.locX = _x;
}
public void setY(int _y){
this.locY = _y;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.BLACK);
g2.fill(oval);
}
}
我不知道为什么它没有正确更新。我以前曾经部分工作过,但是即使用户单击的位置不在椭圆形内,它也会一直更新。
最佳答案
我认为在执行setX
和setY
时,您忘记更新x
中的y
和oval
。您至少有三个选择:
1)每次更改Ellipse2D.Double
和this.locX
时都重新创建this.locY
。
2)希望用oval
一次创建x=0, y=0
,请检查鼠标事件切换到相对坐标(if(oval.contains(e.getX() - locX, e.getY() - locY)){...}
),并使用oval
by AffineTransform
绘制g2.transform(...)
。
3)将椭圆形声明为Ellipse2D.Double oval = new Ellipse2D.Double(...);
,然后可以直接更改其x
和y
,因为它们是公共的:
oval.x = this.locX;
oval.y = this.locY;