简体   繁体   English

在可拖动的jPanel中更改jLabel的文本

[英]changing text of jLabel in a draggable jPanel

In my program, I have a jPanel with a jLabel inside of it. 在我的程序中,我有一个jPanel里面有一个jLabel。 I added this code to make the jPanel draggable, and it works perfectly. 我添加了此代码以使jPanel可拖动,并且它完美地工作。

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. 具体来说,当我单击并拖动以移动面板时,不是跟随鼠标,面板只是排序,而文本更改为~10的值,每当我移动鼠标时都会更改。

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. 让事情变得更加混乱,如果我改变它以便它只是将文本设置为“blah”,它就不会产生错误。 As well, if I just set a variable to be equal to this.getX(), it doesn't produce the error. 同样,如果我只是将变量设置为等于this.getX(),则不会产生错误。 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? 我可以使用一种解决方法来获得相同的效果吗?

When you invoke the setText() method on the label the revalidate() and repaint() methods are invoked on the label. 在标签上调用setText()方法时,会在标签上调用revalidate()repaint()方法。 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. 您可能会发现在这种情况下使用拖动布局

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM