我有一个问题,我似乎无法用我的 Java 代码解决。
我创建了一个显示地图的程序,当您单击地图时,您会在地图上得到一个边缘/节点。当我将两个节点相互连接时,将在连接的点之间显示一条线.
到目前为止一切都很好,或者我想,但是......当x1,y1
坐标的值小于x2,y2
......时很好
我发现是 setBounds 吓到我了……但我不知道如何解决我的问题,而且我似乎在周围的任何地方都找不到任何类似的问题……有没有人遇到过这种问题,如果是这样,你是如何解决这个问题的?
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;
}
}
并且主要(当连接两个节点时):
DrawMyLine dml = new DrawMyLine(from,to);
panel.add(dml);
panel.repaint();
dml.addMouseListener(lineListener);
谁能帮我?请!