Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java basic paint program ugly brush

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?

like image 1000
linksoftwrite Avatar asked Feb 09 '23 19:02

linksoftwrite


1 Answers

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

like image 177
aioobe Avatar answered Feb 12 '23 08:02

aioobe