Adding/Removing Lines from a JPanel

2019-07-11 18:41发布

问题:

I am trying to create a graph implementation where the graph is displayed on a JPanel.

I am adding and removing vertices without a problem (I am using more panels for these). The problem I am having is adding lines to represent the edges. I know I can use

contentPane.getGraphics().drawLine(x1, y1, x2, y2)

to add a line, but it leaves no way for me to delete that line later on. Any ideas?

回答1:

GraphPanel uses a List<Edge> to model edges connecting the nodes of a graph.



回答2:

I don't think that can be done, really... If you just paint the same line in the background color that will of course mess up any other things you have drawn that crosses that line...

The easiest solution would be to redraw the entire control without the line

Only thing I can think of would be if it was possible to create a transparent panel you put inside of the root panel in your control, where you draw that line, like using Layers in Photoshop or GIMP, but not sure about how/if this is possible in Swing.

If you are just trying to get a graph there are several good graph libraries out there...