我应该如何在Java中为我的绘画应用程序拆分连接线

时间:2018-09-20 05:54:32

标签: java swing paintcomponent mousemotionlistener mousemotionevent

我是在Java中使用绘画和线条的新手,如果答案很明显,对不起。一直以来,我都希望线条流畅,这就是为什么我有“ Circles”连接以使线条圆角的原因,问题在于,释放鼠标时无法识别,因此当我尝试书写时另一个字母连接了屏幕上的两个点。对我的应用进行编程以使其在没有连接的情况下具有平滑线条的最佳方法是什么?

package pac;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.geom.Line2D;
import java.util.ArrayList;

import javax.swing.*;

public class Frame extends JPanel{

    private final ArrayList<Point> point = new ArrayList<>();

    public Frame() {
        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.paintComponents(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.setColor(new Color(0, 0, 128));
    g2.setStroke(new BasicStroke(15f,
                                 BasicStroke.CAP_ROUND,
                                 BasicStroke.JOIN_ROUND));
 //   if(!mouserelased) {
        for (int i = 1; i < point.size(); i++)
            g2.draw(new Line2D.Float(point.get(i-1), point.get(i)));
 //   }
    }

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

0 个答案:

没有答案