Rich Hoffman
Rich Hoffman

Reputation: 762

How to handle custom, selectable line class in Java

I've got an application where I'd like for the user to be able to mouse-over and/or right click on a line that is being drawn on a JPanel. I fully expect that I'll implement the line as part of an object that will handle all of the behavior, but I've got a more fundamental question about how to implement the line shown in the below picture. First, the picture:

Arrow Between Two Chassis

I can draw the line itself without any problem, but it's currently just being done in an overridden paintComponent() call in the parent JPanel. I have the rudiments of an idea on how to handle this:

public class ChassisLink extends JComponent implements MouseListener
{
  //Rectangle  to handle mouse-over and right-click for each segment?
    public ChassisLink()
{
    initializeLink();
}

private void initializeLink()
{
    //Init stuff
}

@Override
public void paintComponent(Graphics g)
{
    super.paintComponent(g);
                //Paint the line(s)
}
        //MouseListener events...
//When mouse-over on the line, display a tooltip
//When right clicking, display a different dialog
}

The issue I think I'm failing to understand is how to do the mouseover or click point check. Do I use a Rectangle and check whether the mouse is currently contained in that Rectangle, simply ignoring the triangular parts of the arrows? I'm perfectly sanguine about that. My issue then becomes how I would display these link objects over top of the existing JPanel that contains the chassis objects; it sounds like a candidate for a JLayeredPane, but any confirmation on that path?

Anyway, I appreciate any input people could give me. Feel free to ask for further explanation if something is a bit vague.

Thanks,

-Rich

Upvotes: 2

Views: 368

Answers (1)

ControlAltDel
ControlAltDel

Reputation: 35096

You are on the right track. I would recommend using Area instead of Rectangle - you can get the arrows in that way too, and Area is extremely easy to manipulate using AffineTransforms.

Upvotes: 2

Related Questions