Reputation: 855
Here's my simple code which draws oval near mouse cursor.Each time I click frame is repainted and only one oval can be draw at the time.I would like to know how to make each oval drawn on click to stay on frame.Thank you for each suggestion.
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class Buffer extends JPanel implements MouseListener{
public static JFrame frame;
public static boolean check;
public void paintComponent(Graphics g){
super.paintComponent(g);
if(check==true){
g.drawOval((int)MouseInfo.getPointerInfo().getLocation().getX(), (int)MouseInfo.getPointerInfo().getLocation().getY(), 10, 10);
}
}
public static void main(String args[]){
Buffer x=new Buffer();
x.setBackground(Color.cyan);
frame=new JFrame();
frame.setSize(500,500);
frame.addMouseListener(x);
frame.add(x);
frame.setVisible(true);
}
public void mouseClicked(MouseEvent e){
check=true;
repaint();
}
public void mouseEntered(MouseEvent arg0){}
public void mouseExited(MouseEvent arg0){}
public void mousePressed(MouseEvent arg0){}
public void mouseReleased(MouseEvent arg0){}
}
Upvotes: 1
Views: 822
Reputation: 17007
Make an ArrayList
of objects representing the ovals. In paintComponent
, draw each oval in the list. In the mouse listener, add an oval to the list. Here's an example:
public class Buffer extends JPanel implements MouseListener {
...
private List<Ellipse2D> ovals = new ArrayList<Ellipse2D>();
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
for (Ellipse2D oval : ovals)
g2d.draw(oval);
}
public void mouseClicked(MouseEvent e) {
ovals.add(new Ellipse2D.Double(e.getX(), e.getY(), 10, 10);
repaint();
}
}
Upvotes: 5