繁体   English   中英

从另一个类访问JLabel

[英]Access JLabel from another class

因此,我试图从类“ Controle”访问类“ TesteRotulo”中的(唯一)标签“ lblNewLabel”。

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

}

应该访问TesteRotulo中的标签的Controle类

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

因此,我认为有了TesteRotulo的(唯一)实例的引用,我应该可以访问标签。 但无济于事。 总是得到一个空指针异常。 怎么了? 提前致谢...

您在initialize中的标签是局部变量。 JLabel lblNewLabel = new JLabel();

您应该编写this.lblNewLabel = new JLabel();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM