AgentPaper
AgentPaper

Reputation: 109

changing text of jLabel in a draggable jPanel

In my program, I have a jPanel with a jLabel inside of it. I added this code to make the jPanel draggable, and it works perfectly.

private void formMousePressed(java.awt.event.MouseEvent evt) {                                  
    prevX = evt.getXOnScreen();
}                                 

private void formMouseDragged(java.awt.event.MouseEvent evt) {                                  
    this.setLocation(this.getX() + evt.getXOnScreen() - prevX, this.getY());
    prevX = evt.getXOnScreen();
    // this.labBirthDate.setText(Integer.toString(this.getX()));
}

However, when I added the commented-out code, which updates the label to show the position of the panel, it's stopped working. Specifically, when I click and drag to move the panel, instead of following the mouse, the panel just sort of stutters, and the text changes to a value of ~10, changing whenever I move the mouse.

Making things ever more confusing, if I instead change it so that it just sets the text to "blah", it doesn't produce the error. As well, if I just set a variable to be equal to this.getX(), it doesn't produce the error. If I then set the label to be the value of that local variable, the error comes back.

Does anyone know why this might be happening? Is there a workaround I can use to get the same effect?

Upvotes: 0

Views: 757

Answers (1)

camickr
camickr

Reputation: 324098

When you invoke the setText() method on the label the revalidate() and repaint() methods are invoked on the label. This will cause the layout manager to be invoked and I'm guessing the layout manager will reset the panel to its default position.

If you want to be able to randomly move components around a screen then you need to use a null layout on the parent of the panel that is being dragged. Once you do this you will also need to manually set the size and location of your components.

You might find the Drag Layout handy to use in this case.

Upvotes: 2

Related Questions