【问题标题】:setText method doesn't update JLabel, getText() returns correct stringsetText 方法不更新 JLabel,getText() 返回正确的字符串
【发布时间】:2018-08-31 20:19:34
【问题描述】:

我正在努力解决这个问题 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 Photo here

这个应该已经显示了

“请先阅读我们的服务条款。”

如果有人能真正帮助我,我将不胜感激。谢谢!

编辑,这是解决方案代码,非常感谢@camickr

private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {                                      
    if( prihvaceniuslovi == false ) {
        notification objekt = new notification();
        objekt.setVisible(true);
        objekt.notificationtos();
    }
}

【问题讨论】:

  • 您是否在事件调度线程上调用notificationtos( )

标签: java swing jlabel gettext settext


【解决方案1】:

不需要repaint() 或revalidate() 或paintImmediately()。所需要的只是调用 setText() 方法。

如果框架上的文本没有改变,那么你有两个标签:

  1. 您添加到框架中并
  2. 另一个只是坐在记忆中。

问题可能出在下面的代码上:

new notification().notificationtos();
new notification().setVisible(true);

您不应该继续创建组件的新实例。一个组件应该被创建一次,然后你保存一个引用到你的类中的变量,你可以在将来对组件进行更改。

阅读 How to Use Text Areas 上的 Swing 教程部分。它显示了如何继续将文本添加到同一文本区域。您需要重组您的代码,使其与演示示例类似。

【讨论】:

  • 非常感谢,我已将这两个“新”关键字分成一个对象,并将对象重命名为一个新对象,它有效!
猜你喜欢
  • 1970-01-01
  • 2011-07-25
  • 2017-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-30
相关资源
最近更新 更多