现在我正试着这样做,每当我点击我画的椭圆形内部时,拖动鼠标它会通过重新绘制来移动位置。但是,即使正确检测到MouseEvents,椭圆形图像也不会更新。我很困惑为什么会这样。以下是处理椭圆形,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);
}
}
我无法弄清楚为什么它没有正确更新。之前我有部分工作,但它会一直更新,即使用户点击的位置不在椭圆内。
答案 0 :(得分:0)
我认为您正在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
{1}} AffineTransform
。
3)将椭圆声明为g2.transform(...)
,然后您可以直接更改其Ellipse2D.Double oval = new Ellipse2D.Double(...);
和x
,因为它们是公开的:
y