Search code examples
javaswingjlabel

Change the text of a JLabel - Beginner


My code;

package com.test;

import java.awt.EventQueue;

public class TestGU {

    private JFrame frame;
    private JLabel la;

    /**
     * Launch the application.
     */
    public  void mainM() {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    TestGU window = new TestGU();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void redefine(String text){
         la.setText(text);
    frame.repaint(); 

    }

    /**
     * Create the application.
     */
    public TestGU() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        la = new JLabel("New label");
        frame.getContentPane().add(null);
    }

}

I am trying to change the Text of the Label from the main method (which is a separate class) shown below;

public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {

        TestGU g = new TestGU();
        g.mainM();
        g.redefine("New Value");
}
}

1.) When the main method is executed, i expected the label to have the text "New Value", but it still contains the text New label. Nothing has changed, how can i correct this?


Solution

  • It looks like you are creating two instances of TestGU and your redefine method changes the value of a label on an instance that isn't displayed.

    Just checking my theory now....

    Edit:
    You don't need to create the 2nd instance; your mainM method should be;

    public void mainM() {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    

    PS - I assume that your initialise method actually has this line right?

    frame.getContentPane().add(la);
    

    rather than add(null) as that doesn't work at all.