简体   繁体   中英

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? here are my codes:

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

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

JTextField txt = new JTextField(10);

Better way to addListener to 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 .

According to the principle of OOP a class cannot have more than one member with a single name except in method overloading .

Change the name of the Main -class object from main to main1 or something else. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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