从另一个类访问JLabel

时间:2018-10-17 17:10:08

标签: java swing

因此,我试图从“ 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实例的参考应该可以访问标签。 但无济于事。总是得到一个空指针异常。 怎么了? 预先感谢...

1 个答案:

答案 0 :(得分:1)

您在for i in soup.find_all('tr',{'class':'resultRow'}): 中的标签是局部变量。 initialize

您应该写JLabel lblNewLabel = new JLabel();