OK, bear with me because I'm new to Java and may get some terminology wrong in explaining this...
I have a class based on JPanel filled with some components. I want to have a vertical line drawn when the mouse is dragged. This is to help users line up some of the moveable components.
I have implemented a mouse motion listener for mouseDragged and it is working but I'm having some issues with the line being drawn. It is drawing the line correctly at the mouse cursor location but then it immediately draws another line a bit behind the cursor (and removes the first line). What I THINK is happening is that the draw method for the JPanel is drawing the line in the right place but then the JPanel's components are redrawn the drawline happens again based off of the component position.
I'll post what I think are the relevant parts of the ReportEditBean class.
public void paint(Graphics g) { initializeLayout(); super.paint(g); // Draw vertical line here if (mousePoint_ != null && mousePoint_.x > 0 && mousePoint_.y > 0){ drawLine(g); } } public void drawLine(Graphics g){ g.setColor(Color.LIGHT_GRAY); g.drawLine(mousePoint_.x, mousePoint_.y +500, mousePoint_.x, mousePoint_.y -400); repaint(); }
In the constructor for the class I have the mouse motion event, which seems to be working fine, but I'll include it here as well
long eventMask = AWTEvent.MOUSE_MOTION_EVENT_MASK + AWTEvent.MOUSE_EVENT_MASK; Toolkit.getDefaultToolkit().addAWTEventListener( new AWTEventListener() { public void eventDispatched(AWTEvent e) { if (e instanceof MouseEvent) { Point widgetpt = ReportEditBean.this.getLocationOnScreen(); MouseEvent evt = ((MouseEvent)e); if (evt.getID() == MouseEvent.MOUSE_DRAGGED) { int newX = evt.getX(); // evt.getXOnScreen(); int newY = evt.getY(); // evt.getYOnScreen(); //int newX = evt.getXOnScreen(); //int newY = evt.getYOnScreen(); mousePoint_ = new Point((int) newX, (int)newY); //((MouseEvent)e).getPoint(); Graphics g = reportPanel_.getGraphics(); drawLine(g); } else { mousePoint_ = null; } } } }, eventMask);
Any pointers on what I might have wrong would be appreciated. I'll provide more information if needed.