How to connect two JComponents with line

Hi,

I have GUI which draws different shapes(ovals, rectangles etc) as JComponants on a JPanel . I need to be able to select by clicking a JComponant and connect it to another JComponant on the JPanel. Once I haved established a connection I would like to be able to move the connected JComponants yet maintain the connection. Can you please look at my code and advise as to how this can be achieved.

Thanks.

LineSelector selector = new LineSelector(windowPanel);

windowPanel.addMouseListener(selector);

--

class windowPanel extends JPanel

{

ArrayList lines;

public windowPanel()

{

lines = new ArrayList();

}

protected void paintComponent(Graphics g)

{

super.paintComponent(g);

Graphics2D g2 = (Graphics2D)g;

g2.setColor(Color.white);

g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

RenderingHints.VALUE_ANTIALIAS_ON);

for(int j = 0; j < lines.size(); j++)

g2.draw((Line2D) lines.get(j));

}

protected void addConnectingLine(Component c1, Component c2)

{

Rectangle r1 = c1.getBounds();

Rectangle r2 = c2.getBounds();

lines.add(new Line2D.Double(r1.getCenterX(), r1.getCenterY(),

r2.getCenterX(), r2.getCenterY()));

repaint();

}

}

class LineSelector extends MouseAdapter

{

windowPanel conPanel;

Component firstSelection;

boolean firstComponentSelected;

public LineSelector(windowPanel cp)

{

conPanel = cp;

}

public void mousePressed(MouseEvent e)

{

Point p = e.getPoint();

Component[] c =conPanel.getComponents();

Rectangle rv = new Rectangle();

for(int j = 0; j < c.length; j++)

{

c[j].getBounds(rv);

if(rv.contains(p))

{

if(firstComponentSelected)

{

conPanel.addConnectingLine(c[j], firstSelection);

firstComponentSelected = false;

}

else

{

firstSelection = c[j];

firstComponentSelected = true;

}

break;

}

}

}

}

[2120 byte] By [nat3_16a] at [2007-10-3 3:44:09]
# 1
Hi,these threads can help you http://forum.java.sun.com/thread.jspa?threadID=488823&messageID=2292924 http://forum.java.sun.com/thread.jspa?forumID=20&threadID=607264L.P.
lukika at 2007-7-14 21:40:17 > top of Java-index,Desktop,Core GUI APIs...
# 2
Thanks a lot. Seems good!!! Wiil look at it.Thanks again.
nat3_16a at 2007-7-14 21:40:17 > top of Java-index,Desktop,Core GUI APIs...