Question

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.

Was it helpful?

Solution

Apparently the problem was in the object's constructor. In the original object's creation the program calls for:

public Bmoll(int startX, int startY)
    {
        this.fromX = startX;
        this.fromY = startY;
        this.inverted = false;
        this.staff = Staff.getActiveStaff();
        this.bmoll = GuiHelper.getImage(B_MOLL_FILE);
    }

while, when creating the object for dragging, the empty constructor was called and thus the image object bmoll was null - there was nothing to be drawn.

OTHER TIPS

  1. Make sure you call super.paintComponent
  2. Painting is done within the context of the paint methods, you should never need to call paint or paintComponent yourself
  3. Use paintComponent to paint the current state
  4. When clicked, prepare the state and call repaint
  5. When dragged, update the state and call repaint
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top