Yes, all drawings should be done in the paint...() methods since they will not be drawn immediately anywhere else. The listeners just update the state of the objects to be drawn and call the proper repaint() method to tell the system to draw them.
That piece of code is to determine the position and size of the rectangle that contains the line to be drawn. That panel.repaint() method will only repaint the area bounded by that rectangle (which contains the line) to avoid repainting the whole panel. The logic for x and y determines the top-left most position of the rectangle, and the calculations inside Math.abs determine its width and height. I added 1 to the size calculations since the line to be drawn is 1 pixel wide.
BTW, which flag are you talking about? To optimize the panel drawing, it's probably a good idea to set the doublebuffering flag to true and the opaque flag to false.
That piece of code is to determine the position and size of the rectangle that contains the line to be drawn. That panel.repaint() method will only repaint the area bounded by that rectangle (which contains the line) to avoid repainting the whole panel. The logic for x and y determines the top-left most position of the rectangle, and the calculations inside Math.abs determine its width and height. I added 1 to the size calculations since the line to be drawn is 1 pixel wide.
BTW, which flag are you talking about? To optimize the panel drawing, it's probably a good idea to set the doublebuffering flag to true and the opaque flag to false.