I am making some project which requires dragging objects on the screen. In my main class I have such listener
addMouseMotionListener(new MouseMotionAdapter(){
public void mouseDragged(MouseEvent e){
currentX = e.getX() - 10 ;
currentY = e.getY() - 5;
if(currentNote != null)
{
if(!editingMode)
{
graphics2D.setPaint(Color.BLACK);
currentNote.setParameters(currentX, currentY, NoteDrawing.SKIP_CHECK);
currentNote.paintComponent(graphics2D);
}
else
{
graphics2D.setPaint(Color.BLACK);
currentNote.setParameters(currentNote.getBallFromX(), currentY, NoteDrawing.SKIP_CHECK);
currentNote.paintComponent(graphics2D);
}
}
repaint();
}
})
Now in the object (extending JComponent) which should be painted I have the following paintComponent method:
public void paintComponent(Graphics g) {
g.drawImage(bmoll,fromX, fromY,null);
g.drawLine(fromX, fromY, fromX + 30, fromY);
repaint();
}
and the setting parameters method:
public void setParameters(int x, int y) {
this.fromX = x;
this.fromY = y;
}
When I press the button over the object and then drag the mouse, the line drawn in paintComponent method is dragged properly, the image however is not. The image is not null - it appears on the screen in its original position. If I duplicate the line g.drawImage(bmoll,fromX, fromY,null);
with different coordinates it is being drawn in two places as it should. But when I drag the mouse - nothing happens with it. If anyone has some suggestions about what is causing the problem, I shall be grateful.