
Hi,
I have a query, on every mouse click an oval should be drawn. But in my program I have used repaint() function, therefore previous oval gets erased.How to avoid this so that I get more than one oval.
PFB code snippet of my pgm: public void mouseClicked(MouseEvent m) {
x=m.getX();
y=m.getY();
repaint();
}
public void paint(Graphics g)
{
for(i=0;i<4;i++)
g.drawOval(x,y,30,30);
}
Pls help !

import java.awt.*;
import java.awt.Point;
import javax.swing.*;
import java.awt.event.*;
public class DrawOvalOnMouseClick extends JPanel{
MouseHandler mouseHandler = new MouseHandler();
Point p1 = new Point(0, 0);
Point p2 = new Point(0, 0);
boolean drawing;
public DrawOvalOnMouseClick(){
this.setPreferredSize(new Dimension(500, 400));
this.addMouseListener(mouseHandler);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawOval(p1.x, p1.y, p2.x, p2.y);
}
private class MouseHandler extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
drawing = true;
p1 = e.getPoint();
p2 = p1;
repaint();
}
public void mouseReleased(MouseEvent e) {
drawing = false;
p2 = e.getPoint();
repaint();
}
}
public static void main(String[] args) {
JFrame f = new JFrame("Draw Oval On Mouse Click");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new DrawOvalOnMouseClick());
f.pack();
f.setVisible(true);
}
}
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.