Home > Enterprise >  Draw point on mouse click with Java Swing
Draw point on mouse click with Java Swing

Time:05-05

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.

CodePudding user response:

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);
            }
        });
    }
    
    
}
  • Related