0
正如標題所說,我希望能夠右鍵單擊我在Jpanel上繪製的線條。由於這些行不是組件,我不能簡單地將MouseListener添加到它們。目前,我吸取了我的JPanel線,下面的代碼:如何將鼠標監聽器添加到用Graphics.drawLine繪製的線條()
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
for (UserDrawnLine line : userDrawnLines) {
g.setColor(new Color(line.colorRValue,line.colorGValue, line.colorBValue));
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setStroke(new BasicStroke(line.thickness));
g.drawLine(line.startPointX, line.startPointY, line.endPointX, line.endPointY);
}
}
這是我UserDrawnLine類:
public class UserDrawnLine {
public int startPointX;
public int startPointY;
public int endPointX;
public int endPointY;
public int colorRValue;
public int colorGValue;
public int colorBValue;
public float thickness;
public UserDrawnLine(int startPointX, int startPointY, int endPointX, int endPointY, int colorRValue,int colorGValue,int colorBValue, float thickness) {
this.startPointX = startPointX;
this.startPointY = startPointY;
this.endPointX = endPointX;
this.endPointY = endPointY;
this.colorRValue=colorRValue;
this.colorBValue=colorBValue;
this.colorGValue=colorGValue;
this.thickness=thickness;
}
}
我一直在考慮存儲通過行雲點,然後反應因此當用戶在其中一個點上點擊Jpanel時。但是,這似乎並不是最好的解決方案。有更好的嗎?
['Line2D.contains'](http://docs.oracle.com/javase/8/docs/api/java/awt/geom /Line2D.html#contains-java.awt.geom.Point2D-)總是返回false,因此它絕對不能用於此目的。 – Radiodef
@Radiodef,感謝您的澄清。該選項已被刪除。 – copeg
@copeg非常感謝,你的解決方案就像一個魅力:) – Endrew