![](/img/trans.png)
[英]How can i draw a line between two points created as a result of a mouse click
[英]Dynamic Line between two points, click, move mouse, then click
我必須用Java畫一條線。 我單擊一個點,然后釋放鼠標鍵,移動鼠標(行的末尾應位於鼠標光標所在的位置(動態預覽)),然后再次單擊鼠標鍵以完成該行。
我在這里看到了各種各樣的問題,但大多數問題都是按住鼠標按鈕並拖動鼠標。
我的問題是,如何使用上述方法動態繪制一條線。 我擔心重新粉刷。 我之前有代碼,當我移動鼠標時它畫了所有的線。 有沒有一種方法可以預覽。
您需要創建一個同時實現MouseEventListener
和MouseMotionListener
的應用程序。 使用MouseEventListener
方法mouseClicked
來檢查是否單擊了鼠標,然后使用MouseMotionListener
方法MouseMoved
將行的另一端更新到鼠標的位置。 最后,再次使用MouseEventListener
來精確定位行的結束位置。
我希望這有幫助。
看看: http : //docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html和http://docs.oracle.com/javase/tutorial/uiswing/events/mousemotionlistener.html 。
您的帖子中遺漏了很多信息,因此很難提供確切的解決方案,但這是基本思路。 假設您需要一個透明的JComponent來接收鼠標事件並繪制您的行預覽,那么代碼將如下所示。
public class MyLinePreviewComponent extends JComponent {
Point sourcePoint;
Point destinationPoint;
pubic MyLinePreviewComponent() {
this.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (sourcePoint == null)
sourcePoint = e.getPoint();
else
sourcePoint = null;
repaint();
}
});
this.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
if (sourcePoint != null)
targetPoint = e.getPoint();
repaint();
}
});
}
public void paintComponent(Graphics g) {
if (sourcePoint != null && destinationPoint != null) {
g.setColor(Color.red);
g.drawLine(sourcePoint.x, sourcePoint.y, destinationPoint.x, destinationPoint.y);
}
}
}
請注意,我沒有運行此代碼。
如果必須將行預覽功能添加到現有組件,則必須在繪制行之前重新繪制paintComponent()中的常規內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.