Java basic paint program ugly brush

2.5k views Asked by At
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;

public class Circle extends JPanel {
private final ArrayList<Point> point = new ArrayList<>();

public Circle() {
    addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent event) {
            point.add(event.getPoint());
            repaint();
        }
    });

    addMouseMotionListener(new MouseMotionAdapter() {
        public void mouseDragged(MouseEvent event) {
            point.add(event.getPoint());
            repaint();
        }
    });
}

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(new Color(0, 0, 128));
    for (Point p : point)
        g.fillOval(p.x, p.y, 15, 15);
}

public static void main(String[] args) {
    JFrame f = new JFrame();
    f.add(new Circle());
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(800, 600);
    f.setVisible(true);
}
}

Here is sample program.

Drawing it display ugly gap:

enter image description here

I looked many tutorials for java paint, but everytime their explanation is like the above sample program. How can Java make smooth brush style like Microsoft Paint?

2

There are 2 answers

0
Jan On

Your code paints a lot of single points, so if you move the mouse quickly, you will have gaps. At the point, where you draw the filled oval, you have to add something to connect the current point to the previous.

0
aioobe On

You need to draw lines between the points instead of ovals at each point. Here's a slightly modified paintComponent method:

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.setColor(new Color(0, 0, 128));
    g2.setStroke(new BasicStroke(15f,
                                 BasicStroke.CAP_ROUND,
                                 BasicStroke.JOIN_ROUND));
    for (int i = 1; i < point.size(); i++)
        g2.draw(new Line2D.Float(point.get(i-1), point.get(i)));
}

Result:

enter image description here