I have a GUI that displays a graph and I want to have some help with a code that allows you to click a point and then another point and then it draws a line. I need some help with this because I don't know were to start. ;)

Dani AI

Generated

Short answer: attach a mouse listener to the component that shows the graph, record the first click, and on the second click create a persistent line and request a repaint. As suggested, you need to capture two clicks; and as pointed out, the MouseEvent gives you the click location. A simple, reliable state model is a nullable "first point" variable plus a collection that holds every completed line so they persist across repaints.

Important implementation notes: do not draw directly from the mouse handler by grabbing the component Graphics — instead update your model (the stored points/lines) and call repaint. Put all drawing in the component’s paintComponent so Swing can manage refreshes and double buffering; call super.paintComponent(g) first. For immediate visual feedback while the user moves the mouse after the first click, add a MouseMotionListener and draw a temporary "rubber-band" line during paintComponent using the stored first point and the current mouse position.

If the graph uses a different coordinate system than pixels, convert between logical (data) coordinates and screen coordinates explicitly. Store logical coordinates if lines should remain correct when zooming or panning, and map to pixel coordinates only when painting. For many persistent lines or a complex background, cache the static parts in a BufferedImage and draw only overlays each repaint to improve performance.

Troubleshooting tips: use a nullable point rather than a boolean to avoid state bugs; call repaint() after updating your model; ensure listeners run on the EDT (use SwingUtilities.invokeLater if needed); and add a small movement threshold if you need to distinguish clicks from tiny drags.

Recommended Answers

All 4 Replies

Dear u can do this by seving both left buton click in 2 variabli and just use drawline funcrion for drawing a line

In the MouseEvent's you can do this to get the location of the click:

Event.getX();

Event.getY();

That would help you with the coordinates of where the click happened, and where you should draw the line.

ok but how is that info stored?

you can store it in a double:

double x1 = Event.getX();

double y2 = Event.getY();

I don't know how you are going to tell if the first points were clicked unless you use a boolean...Like that boolean is set to true if the frst points are clicked, and then set to false..If that boolean is set to false, y would then store to the points in the second set of coordinates:

double x2 = Event.getX();
double y2 = Event.getY();

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.