简体   繁体   中英

Draw point on mouse click with Java Swing

I'm working on a project in which I am trying to draw point on mouse click within a JPanel with Java Swing.

I save each time the clicked points coordinate in currentX and currentY and create an Ellipse2D List with those coordinates but it doesn't work.

I solved it and it works: Below the solution:

package progetto;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 *
 * @author Anna
 */
public class MapDrawer extends JPanel{
    
    private List<Point> points = new ArrayList<>();
    
    public MapDrawer(){
        setBackground(new Color(23,99,8));
        addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e){
                points.add(new Point(e.getX(), e.getY()));
                repaint();
            }
        });
    }
    
    @Override
    public void paintComponent (Graphics g){
        super.paintComponent(g);
        Graphics g2 = (Graphics2D) g;
        g2.setColor(Color.gray);
        for (Point p : points){
            g2.fillOval(p.x, p.y, 5, 5);
        }
    }
    
    public static void main(String [] args){
        EventQueue.invokeLater(new Runnable(){
            @Override
            public void run(){
                JFrame frame = new JFrame();
                frame.add(new MapDrawer());
                frame.setSize(400,400);
                frame.setVisible(true);
            }
        });
    }
    
    
}

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