【问题标题】:Get variable from class to another class从类获取变量到另一个类
【发布时间】:2013-10-04 20:06:25
【问题描述】:

我无法将class main 的变量传递给另一个类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

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

【问题讨论】:

  • 为什么有两个main() 方法?
  • 因为它只是我系统的简化代码..
  • 我看到 txt 正在初始化,但我看不到它的 text 属性集。例如txt.settext(somestring);
  • 我已经试过了,但也没试过..

标签: java class oop variables getter-setter


【解决方案1】:

Members-class 的代码中两个名为main的成员,它们是一个Main-class 对象main()-方法

根据OOP的原则,一个类不能有多个同名的成员除了方法重载

Main-class 对象的名称从main 更改为main1 或其他名称。希望这能解决您的问题。

使用下面的代码sn-p-

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

【讨论】:

  • 仍然得到一个空值.. =[
  • @PhantomKid 你应该交叉检查在后台运行的其他类。修改后的代码应该可以正常运行了。
【解决方案2】:

在你的场景中,你会得到空值,因为值是在构造函数中设置的

this.value = txt.getText(); 

确保在更新文本字段时更新 this.value

JTextField txt = new JTextField(10);

将Listener添加到txt的更好方法

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

【讨论】:

    猜你喜欢
    • 2020-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多