[英]Get variable from class to another class
我在将class main
的变量传递给另一个class class members
遇到了麻烦。我尝试使用getter-setter方法,但是它只返回一个null
值,我该如何解决呢? 这是我的代码:
Main.java
public class Main extends JFrame{
JTextField txt = new JTextField(10);
String value;
Main(){
getContentPane().add(txt);
this.value = txt.getText();
setLayout(new FlowLayout());
setSize(300,200);
setVisible(true);
}//constructor of main
public String getValue(){
return this.value;
}//getValue
public static void main(String args[]){
new Main();
}//psvm
}//class main
成员.java
public class Members extends JFrame{
JLabel lbl = new JLabel("");
Main main = new Main();
Members(){
getContentPane().add(lbl);
main.setVisible(false);
lbl.setText(main.getValue());
setLayout(new FlowLayout());
setSize(300,200);
setVisible(true);
}//constructor of main
public static void main(String args[]){
new Members();
}//psvm
}//class members
在您的方案中,您将获得空值,因为在构造函数中设置了值
this.value = txt.getText();
确保在更新文本字段时更新this.value
JTextField txt = new JTextField(10);
将侦听器添加到txt的更好方法
txt.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
//update value
}});
在您的Members
class的代码中,有两个名为main
成员 ,这是一个Main
class对象和main()
-method 。
根据OOP的原理, 除了方法重载外,一个类不能有一个以上的具有单个名称的成员。
将Main
-class对象的名称从main
更改为main1
或其他名称。 希望这能解决您的问题。
使用以下代码段-
public class Members extends JFrame{
JLabel lbl = new JLabel("");
Main main1 = new Main();
Members(){
getContentPane().add(lbl);
main1.setVisible(false);
lbl.setText(main1.getValue());
setLayout(new FlowLayout());
setSize(300,200);
setVisible(true);
}//constructor of main
public static void main(String args[]){
new Members();
}//psvm
}//class members
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.