java - How to add mouse listener to lines drawn with Graphics.drawLine() -


as title says, want able right-click lines i've drawn on jpanel. since lines aren't components can't add mouselistener them. i'm drawing lines on jpanel following code:

@override public void paintcomponent(graphics g) {     super.paintcomponent(g);     graphics2d g2d = (graphics2d) g;     (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);     } } 

this userdrawnline class:

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;     } } 

i've been thinking storing points through line goes , reacting accordingly when user clicks on jpanel on 1 of points. doesn't seem best solution. better ones?

create collection lines and, using point provided mouseevent in mouselistener, iterate on collection , check if point on each line. may have roll own line class , implement contains method (note line2d cannot used it's contains method returns false).

to determine if point p on line:

distance(p, a) + distance(p, b) = distance(a,b)

where a , b line endpoints, , p test point. 1 can use error term allow points near not on line (for instance, when using wider strokes render, might wish increase error term). assuming class has endpoints a , b:

public boolean contains(point p, double error){     double dist = math.sqrt(math.pow(p.x - a.x, 2) + math.pow(p.y - a.y, 2)) +              math.sqrt(math.pow(p.x - b.x, 2) + math.pow(p.y - b.y, 2));     return math.abs(dist - this.distance) <= error; } 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -