在JFrame上绘制的点的总距离

时间:2016-03-12 19:52:18

标签: java swing

我正在尝试打印总距离,就像你可以看到我有page.drawString(“距离:”+ fmt.format(长度),10,15);在我的代码中。但是这只增加了从point1到point2的长度。我希望它继续添加例如我从点1到点2绘制一条距离为30的线然后再次从点1到点2绘制一条距离为20的线因此我的drawString应该显示50作为结果。

{{1}}

1 个答案:

答案 0 :(得分:2)

解决方法是简单地为您的班级提供double totalDistance字段,将其初始化为0,然后在计算后立即将每个计算出的长度添加到totalDistance字段。

public class RubberLinesPanel extends JPanel {
    private Point current = null, point2 = null;
    private double length;
    private double totalDistance = 0.0;  // ***** add this *****
    private DecimalFormat fmt;

    public RubberLinesPanel() {
        // .... etc .....
    }

    public void paintComponent(Graphics page) {
        super.paintComponent(page);
        page.setColor(Color.yellow);
        if (current != null && point2 != null)
            page.drawLine(current.x, current.y, point2.x, point2.y);
        page.drawString("Distance: " + fmt.format(length), 10, 15);

        // draw totalDistance here  // ************ draw it here
    }

    private class LineListener implements MouseListener, MouseMotionListener {

        public void mousePressed(MouseEvent event) {
            current = event.getPoint();
        }

        public void mouseDragged(MouseEvent event) {
            point2 = event.getPoint();
            length = Math.sqrt(Math.pow((current.x - point2.x), 2)
                    + Math.pow((current.y - point2.y), 2));
            totalDistance += length;   // ******* calculate it here
            repaint();
        }

或者我是否过度简化了您的问题,因为此解决方案似乎过于简单了?