Reputation:
I want to be able to click the circle, in which it will change position and change the circle. I am not sure how to implement the mouse listener.
Is there a way to put a mouse listener in a new class in which it will change the position of the x and y, and change the color?
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);
}
}
Upvotes: 0
Views: 60
Reputation: 324078
For a fancier implementation you can take a look at Playing With Shapes. The ShapeComponent
class will allow you to create a real component that can support a MouseListener so it is easy to respond to MouseEvents.
You should not be setting the (random) Color of your circle in the paintComponent() method. The paintComponent() method is invoked whenever Swing determines the component needs to be repainted. Therefore the color could potentially change without any user interaction. Instead the color of your circle should probably be set by using the setForeground(...)
method. Then the painting code can use the getForeground()
method for the circle.
Also, whenever you do custom painting you need to override the getPreferredSize()
method to set the size of your component so it can be used with layout managers. Read the section from the Swing tutorial on Custom Painting for more information.
Upvotes: 2
Reputation: 285415
I would use something that is "clickable" such as an Ellipse2D object, since like all classes that implement Shape, it has a contains(...)
method that can be useful for deciding if any circle(s) have been clicked on, and it can be drawn easily by casting your paintComponent's Graphics parameter to Graphics2D and then calling its fill(Shape s)
method, passing your Ellipse2D object in.
Upvotes: 3