简体   繁体   中英

How to draw a filled oval where a mouse clicked on Jpanel

I want to write a code to draw a filled oval where ever the mouse is clicked inside a panel. I used to develop some codes but unfortunately when I tried to do the next click the whole panel blanked and new point appeared. I want to keep the previous points and add some new ones by the next user's click on the panel. How do I implement the paint component of MyPanel ? Here is my code; it does not work properly, because it produces some small points instead of rectangle.

class MyPanel extends JPanel {
Point pointClicked;

public MyPanel() {
     this.addMouseListener(new MouseAdapter() {
        @Override
         public void mouseClicked(MouseEvent e) {
             pointClicked = e.getPoint();
         }
     });
}
@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.fillRect(pointClicked.x, pointClicked.y, 1, 1);
}
}

I want to keep the previous points and add some new ones by the next user's click on the panel.

You need to keep track of each oval painted and repaint all ovals each time the paintComponent() method is called.

Check out Custom Painting Approaches for two different ways to do this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM