setText方法不更新JLabel,getText()返回正确的字符串

问题描述 投票:0回答:1

我正在努力解决这个问题2个小时,但仍然没有发生任何事情。我尝试使用revalidate,paintImmediate等多种方法更新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

这个应该已经显示出来了

“请先阅读我们的ToS。”

如果有人真的可以帮助我,我将非常感激。谢谢!

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

private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {                                      
    if( prihvaceniuslovi == false ) {
        notification objekt = new notification();
        objekt.setVisible(true);
        objekt.notificationtos();
    }
}
java swing jlabel gettext settext
1个回答
2
投票

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

如果文本没有在框架上更改,那么您有两个标签:

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

问题是下面的代码:

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.