I have a problem that I can't seem to fix with my Java code.
I've created a program that shows a map, when u click on the map, u get a edge/node dotted out on the map.. When I connect two nodes with each other, a line is to be shown between the connected dots.
So far so good, or so I thought, but... It's fine when the x1,y1
coordinates have values that are less than x2,y2
...
I've figured out that it's the setBounds that been spooking me... But I dont know how to solve my problem, and I can't seem to find any simular problem anywhere around... Has anyone come across this kind of problem, and if so, how did you solve this?
import java.awt.*;
import javax.swing.*;
public class DrawMyLine extends JComponent{
private int fx, fy, tx, ty;
private int h,w;
private int m;
private double k;
private Destinations from;
private Destinations to;
public DrawMyLine(Destinations from, Destinations to){
this.from=from;
this.to=to;
setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
fx = from.getX();
fy = from.getY();
tx = to.getX();
ty = to.getY();
//w = Math.abs(tx - fx);
//h = Math.abs(ty - fy);
w = tx - fx;
h = ty - fy;
int x,y;
if(ty>fy){ //This is my, not so great solution so far...
x = fx;
y = fy;
}
else{
x = tx;
y = ty;
}
setBounds(x+5,y+5, w, h); //How do I reverse the boundary?
setPreferredSize(new Dimension(w, h));
setMinimumSize(new Dimension(w, h));
setMaximumSize(new Dimension(w, h));
}
//@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.BLACK);
g.drawLine(0,0,w,h);
}
//Method to reduce the clickable area to 5 pixels from the line
public boolean contains(int x, int y){
k = ((ty-fy)/(tx-fx));
if(k >= 0){
m = 0;
}
else{
m = ty - fy;
}
return Math.abs(y - k * x - m) < 5;
}//contains
public Destinations getFrom(){
return from;
}
public Destinations getTo(){
return to;
}
}
And in the main(when two nodes are connected):
DrawMyLine dml = new DrawMyLine(from,to);
panel.add(dml);
panel.repaint();
dml.addMouseListener(lineListener);
Can anyone help me? Please!