简体   繁体   English

从一个类到另一个类获取变量

[英]Get variable from class to another class

I'm having trouble getting the variable of class main to another class class members ... Ive tried using getter-setter but it only return me a null value, how can i fix it? 我在将class main的变量传递给另一个class class members遇到了麻烦。我尝试使用getter-setter方法,但是它只返回一个null值,我该如何解决呢? here are my codes: 这是我的代码:

Main.java 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

Members.java 成员.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

In your scenario, you will get null value because value is being set in constructor 在您的方案中,您将获得空值,因为在构造函数中设置了值

this.value = txt.getText(); 

Make sure that, you update the this.value whenever you update the textfield 确保在更新文本字段时更新this.value

JTextField txt = new JTextField(10);

Better way to addListener to txt 将侦听器添加到txt的更好方法

txt.getDocument().addDocumentListener(new DocumentListener() {
     public void changedUpdate(DocumentEvent e) {
    //update value
   }});

In the code of your Members -class there are two members named main which are one Main -class object and a main() -method . 在您的Members class的代码中,两个名为main成员 ,这是一个Main class对象main() -method

According to the principle of OOP a class cannot have more than one member with a single name except in method overloading . 根据OOP的原理, 除了方法重载外,一个类不能有一个以上的具有单个名称的成员。

Change the name of the Main -class object from main to main1 or something else. Main -class对象的名称从main更改为main1或其他名称。 Hope this will solve your problem. 希望这能解决您的问题。

Use the following code snippet- 使用以下代码段-

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.

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