Search code examples
javaswingjlabelgettextsettext

setText method doesn't update JLabel, getText() returns correct string


I am struggling to fix this for like 2 hours and still nothing really happened. I've tried updating the JLabel with multiple methods like revalidate, paintImmediately, etc, although it didn't change the final result.

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);
    }
}

Also on debugging, here's the output from the code above:

run:
debug
Read our ToS first, please.
BUILD SUCCESSFUL (total time: 3 seconds)

GUI shows up normally, but the string isn't being changed from the one that's been set on initialization of the JLabel.

Instead of this string below that's been shown in photo... GUI Photo here

this one should've been shown

"Read our ToS first, please."

I would be very grateful if someone could actually help me. Thanks!

EDIT, Here's the solution code, thanks alot @camickr

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

Solution

  • There is no need for repaint() or revalidate() or paintImmediately(). All that is needed is to invoke the setText() method.

    If the text doesn't change on the frame then you have two labels:

    1. One that you added to the frame and
    2. another one that is just sitting in memory.

    The problem would be the code below:

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

    You should NOT keep creating new instances of a component. A component should be created once and then you save a refrence to the variable in your class that that you can make changes to the component in the future.

    Read the section from the Swing tutorial on How to Use Text Areas. It shows how you can keep adding text to the same text area. You need to restructure your code to be similar to the demo example.