0

So, I'm trying to access the (only) label "lblNewLabel" in class "TesteRotulo" from class "Controle".

public class TesteRotulo {

    private JFrame frame;
    private JLabel lblNewLabel;

    // getter for the label to be accessed by class Controle
    public JLabel getLblNewLabel() {
        return lblNewLabel;
    }

    /**
    * Launch the application.
    */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    TesteRotulo window = new TesteRotulo();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
    * Create the application.
    */
    public TesteRotulo() {
        initialize();
        // instantiate new object Controle having this instance of Testerotulo as parameter
        Controle c = new Controle(TesteRotulo.this);
        c.setRotulo();
    }


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

        JLabel lblNewLabel = new JLabel();
        frame.getContentPane().add(lblNewLabel, BorderLayout.CENTER);
        frame.setVisible(true);
     }

}

The class Controle that should access the label in TesteRotulo

public class Controle {

    private TesteRotulo jM;
    private JFrame janela;
    private JLabel rotulo;

    public Controle(TesteRotulo jM) {
        this.jM = jM;
    }
    public void setRotulo() {
        this.rotulo = jM.getLblNewLabel();
        rotulo.setText("teste");
    }
}

So I think having the reference for the (only) instance of TesteRotulo I should be able to access the label. But to no avail. Always get a null pointer exception. What is wrong? Thanks in advance...

Rans
  • 422
  • 2
  • 8
Gorducho
  • 3
  • 4

1 Answers1

1

Your label in initialize is a local variable. JLabel lblNewLabel = new JLabel();

You should write this.lblNewLabel = new JLabel();

pL4Gu33
  • 2,045
  • 16
  • 38
  • Thank you very much! I did the GUI in real Project (to show "n" images in the label) via Eclipse Window Builder and went over this! – Gorducho Oct 17 '18 at 17:28