[英]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.