Java基本绘画程序难看刷

时间:2015-06-16 15:04:50

标签: java swing paintcomponent

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

以下是示例程序。

绘制它显示丑陋的差距:

enter image description here

我看了很多关于java paint的教程,但每次他们的解释都像上面的示例程序一样。 Java如何像Microsoft Paint一样制作流畅的笔刷样式?

2 个答案:

答案 0 :(得分:7)

您需要在每个点之间绘制线而不是椭圆。这是一个略微修改过的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)));
}

<强>结果:

enter image description here

答案 1 :(得分:0)

您的代码会绘制很多单点,因此如果您快速移动鼠标,则会产生间隙。在绘制填充椭圆的位置,您必须添加一些内容以将当前点连接到上一个。