0
我想打印總距離,就像你可以看到我有page.drawString(「Distance:」+ fmt.format(length),10,15);在我的代碼中。但是這僅增加了從點1到點2的長度。我希望它繼續添加例如我畫一條線從點1到點2有30的距離,然後再次畫了一條線從點1到點2有20的距離,所以我的drawString應該顯示爲50結果。在JFrame上繪製點的總距離
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
public class RubberLinesPanel extends JPanel {
private Point current = null, point2 = null;
private double length;
private DecimalFormat fmt;
public RubberLinesPanel() {
LineListener listener = new LineListener();
addMouseListener(listener);
addMouseMotionListener(listener);
setBackground(Color.black);
setPreferredSize(new Dimension(400, 200));
fmt = new DecimalFormat("0.##");
}
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);
}
private class LineListener implements MouseListener, MouseMotionListener {
public void mousePressed(MouseEvent event) {
current = event.getPoint();
}
//--------------------------------------------------------------
// Gets the current position of the mouse as it is dragged and
// redraws the line to create the rubberband effect.
//--------------------------------------------------------------
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));
repaint();
}
//--------------------------------------------------------------
// Provide empty definitions for unused event methods.
//--------------------------------------------------------------
public void mouseClicked(MouseEvent event) {}
public void mouseReleased(MouseEvent event) {}
public void mouseEntered(MouseEvent event) {}
public void mouseExited(MouseEvent event) {}
public void mouseMoved(MouseEvent event) {}
}
}
請避免使用所有的大寫字母,因爲它等同於**在本網站和其他網站上發佈**。謝謝 –
我編輯了您的問題標題並刪除了全部大寫。 –
我看到喊大聲笑大聲笑 – xenon