The basic Java drawing program

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 an example program.

Draw a display of the ugly gap:

enter image description here

I looked through many tutorials for java paints, but each time their explanation is similar to the above sample program. How can Java make a smooth brush style like Microsoft Paint?

+4
source share
2 answers

You need to draw lines between points instead of ovals at each point. The method is slightly modified here paintComponent:

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

+7
source

Your code draws a lot of individual points, so if you quickly move the mouse, you will have spaces. At the point where you draw the filled oval, you need to add something to relate the current point to the previous one.

0
source

All Articles