gpt4 book ai didi

java - 从另一个类访问 JLabel

转载 作者:行者123 更新时间:2023-12-02 10:42:01 24 4
gpt4 key购买 nike

因此,我正在尝试从“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();

关于java - 从另一个类访问 JLabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52860239/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com