2014-06-28 54 views
0

我希望能够点击其中将改变位置并更改圆的圆。我不知道如何实现鼠标监听器。如何以正确的方式使用鼠标侦听器?

有没有把鼠标监听器在一个新的类中,它会改变x和y的位置,并改变颜色的方法吗?

class drawCircle extends JPanel{  

    int x = 70; 
    int y = 70; 
    int dx = 0; 
    int dy = 0; 

drawCircle(){ 
    addMouseMotionListener(new MouseMotionAdapter(){ 
     public void mousePressed(MouseEvent e){ 

      x = (int)(Math.random()*getWidth() - 70); 
      y = (int)(Math.random()*getHeight() - 70); 
      repaint(); 
      } 

    }); 
} 


protected void paintComponent(Graphics g){ 
super.paintComponent(g); 

    int red = (int)(Math.random()*255); 
    int blue =(int)(Math.random()*255); 
    int green = (int)(Math.random()*255); 

    Color color = new Color(red,blue,green); 

    g.setColor(color); 
    g.fillOval(x + dx, y +dy, x + dx, y + dy); 
    g.drawString(" ", x + dx, y + dy); 


} 

}

回答

4

我会用的东西是“点击”,如Ellipse2D的对象,因为实现形状像所有的类,它有一个contains(...)方法,可以为如果任何圈子决定是有用的( s)已被点击,并且可以通过将您的paintComponent的Graphics参数转换为Graphics2D,然后调用其方法fill(Shape s),将您的Ellipse2D对象传入,从而轻松绘制该图像。

+0

+1简单直接。 – camickr

3

对于更新的实现,您可以查看Playing With ShapesShapeComponent类将允许您创建一个可支持MouseListener的实际组件,以便轻松响应MouseEvents。

您不应该在paintComponent()方法中设置圆的(随机)颜色。每当Swing确定组件需要重新绘制时,paintComponent()方法都会被调用。因此,无需任何用户交互,颜色可能会发生变化。相反,您的圈子的颜色应该可以使用setForeground(...)方法进行设置。然后绘制代码可以使用该圆的getForeground()方法。

而且,只要你的风俗画,你需要重写getPreferredSize()方法来设置组件的大小,因此它可以与布局管理器一起使用。阅读Swing教程Custom Painting中的部分以获取更多信息。

相关问题