how to determine on what segment a point is in
i have line segments that are connected and assuming that i can get the points of the segments, how do i know on what segment the point is in?
i have line segments that are connected and assuming that i can get the points of the segments, how do i know on what segment the point is in?
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
public class ProximityTest extends JPanel {
Color[] colors = { Color.red, Color.green.darker(), Color.blue };
Line2D.Double[] lines;
Point probe;
Point offset = new Point(5,20);
JLabel lineLabel;
JLabel distLabel;
public ProximityTest() {
lines = new Line2D.Double[3];
lines[0] = new Line2D.Double(50,50,350,250);
lines[1] = new Line2D.Double(50,350,375,150);
lines[2] = new Line2D.Double(100,50,150,350);
probe = new Point();
addMouseMotionListener(mml);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
for(int j = 0; j < lines.length; j++) {
g2.setPaint(colors[j]);
g2.draw(lines[j]);
}
g2.setPaint(Color.red);
g2.fill(new Ellipse2D.Double(probe.x-2,probe.y-2,4,4));
}
private void checkProximity() {
int index = -1;
double min = Double.MAX_VALUE;
for(int j = 0; j < lines.length; j++) {
double distance = lines[j].ptSegDist(probe);
if(distance < min) {
min = distance;
index = j;
}
}
lineLabel.setForeground(colors[index]);
distLabel.setText(String.format("%.1f", min));
}
private JPanel getLast() {
lineLabel = new JLabel("line");
distLabel = new JLabel(" ");
Dimension d = distLabel.getPreferredSize();
d.width = 45;
distLabel.setPreferredSize(d);
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(2,2,2,2);
gbc.anchor = GridBagConstraints.WEST;
gbc.weightx = 1.0;
panel.add(new JLabel(), gbc);
gbc.weightx = 0;
panel.add(new JLabel("closest"), gbc);
panel.add(lineLabel, gbc);
panel.add(distLabel, gbc);
gbc.weightx = 1.0;
panel.add(new JLabel(), gbc);
return panel;
}
public static void main(String[] args) {
ProximityTest test = new ProximityTest();
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(test);
f.getContentPane().add(test.getLast(), "Last");
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
}
private MouseMotionListener mml = new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
Point p = e.getPoint();
probe.setLocation(p.x-offset.x, p.y-offset.y);
checkProximity();
repaint();
}
};
}