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:
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?
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With