[英]JLabel on JPanel doesn't update when setText from another method
[英]setText method doesn't update JLabel, getText() returns correct string
我努力将其修复了大约2个小时,但实际上没有任何反应。 我尝试使用多种方法(如revalidate,paintImmediately等)更新JLabel,尽管它没有改变最终结果。
public void notificationtos( ) { jLabel2.setText( "Read our ToS first, please." ); jLabel2.revalidate(); jLabel2.paintImmediately(jLabel2.getVisibleRect()); System.out.println("debug" ); System.out.println( jLabel2.getText() ); } private void jButton1MouseClicked(java.awt.event.MouseEvent evt) { if( prihvaceniuslovi == false ) { new notification().notificationtos(); new notification().setVisible(true); } }
同样在调试时,这是上面代码的输出:
run: debug Read our ToS first, please. BUILD SUCCESSFUL (total time: 3 seconds)
GUI可以正常显示,但是该字符串与JLabel初始化时设置的字符串相同。
而不是下面的字符串显示在照片中... GUI照片在这里
这个应该已经展示了
“请先阅读我们的服务条款。”
如果有人可以帮助我,我将不胜感激。 谢谢!
编辑,这是解决方案代码,非常感谢@camickr
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) { if( prihvaceniuslovi == false ) { notification objekt = new notification(); objekt.setVisible(true); objekt.notificationtos(); } }
不需要repaint()或revalidate()或paintImmediately()。 所需要做的就是调用setText()方法。
如果文本在框架上没有变化,则您有两个标签:
问题可能是以下代码:
new notification().notificationtos();
new notification().setVisible(true);
您不应该继续创建组件的新实例。 应该一次创建一个组件,然后在类中保存对变量的引用,以便将来可以更改该组件。
阅读Swing教程中有关如何使用文本区域的部分 。 它显示了如何继续将文本添加到同一文本区域。 您需要重组代码,使其与演示示例相似。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.