【问题标题】:Use a String in another class在另一个类中使用字符串
【发布时间】:2013-12-17 14:08:37
【问题描述】:

我正在开发一个有 2 个类的程序。第一个仅用于程序的 GUI。另一个是使用所需数据创建新文件的代码。

我想使用用户在 jTextField 中写入的文本。但我的问题是,我无法将文本保存在字符串中,而是在另一个类中使用代码调用它来保存用户输入。

所以在 NetworkComponentFrame 类中有以下代码:

public class NetworkComponentFrame extends javax.swing.JFrame {
/* GUI Code */
public static void main(String args[]) {
String ID = jTextField1.getText();
/* other code */
}}

而在NetworkComponent类中,此刻的代码如下:

public class NetworkComponent {
public static void New(){
NetworkComponentFrame ID = new NetworkComponentFrame();
/*other code */}}

名称只是一些占位符。我希望这些信息足以帮助我解决问题。

【问题讨论】:

  • 也许为可以在其他类中调用的字符串创建一个公共的getter/setter?

标签: java class object user-interface


【解决方案1】:

您可以通过创建构造函数 NetworkComponent 或 NetworkComponentFrame 类的静态属性来传递值。 例如

public class NetworkComponentFrame extends javax.swing.JFrame {
/* GUI Code */
public String ID;
public static void main(String args[]) {
ID = jTextField1.getText();
/* other code */
}}

在你的第二堂课

public class NetworkComponent {
public static void New(){
s.o.p(NetworkComponentFrame.ID);
/*other code */}}

【讨论】:

    【解决方案2】:

    如果我理解正确,您可以在主函数之外定义字符串 ID,但在 NetworkComponentFrame 类中将其定义为公共的,因此您可以在从您的类创建对象后随时随地访问它。

    例如:

    public class NetworkComponentFrame extends javax.swing.JFrame {
    public String ID_text;
    /* GUI Code */
    public static void main(String args[]) {
    ID_text = jTextField1.getText();
    /* other code */
    }}
    
    
    public class NetworkComponent {
    public static void New(){
    NetworkComponentFrame ID = new NetworkComponentFrame();<
    String test = ID.ID_text;
    /*other code */}}
    

    您的示例代码有问题。你确定你在非静态对象中调用 public static void main 函数吗?

    扩展:U 也可以使用 getter 和 setter。

    【讨论】:

    • 这对我帮助很大,但如果我只是做一个 System.out.println(ID_text);在 NetworkComponentFrame 类中。 --> 输出是对的。但在另一个类中是输出“null”。问题出在哪里?
    【解决方案3】:

    我认为您希望反过来。在 GUI 中实例化 NetworkComponent 并在 NetworkComponent 中有一个 setter 方法,并使用文本字段中的文本来设置 NetworkComponent 对象中的文本。

    public class NetworkComponent {
        String ID;
    
        public void setId(String text){
            ID = text;
        }
    }
    
    public class NetworkComponentFrame extends javax.swing.JFrame {
        NetworkComponent network = new NetWorkComponent();  <-- NetworkComponent object
        JButton button = new JButton();
        JTextField textField = new JTextField();
    
        public NetworkComponentFrame(){
            button.addActionListener(new ActionListener(){
                public actionPerformed(ActionEvent e){
                    String text = textField.getText();
                    network.setId(text);                   <-- set the ID here
                }
            });
        }
    }
    

    【讨论】:

    • 我知道这听起来很有趣,但老师说过,我必须这样做:/但还是谢谢
    • 告诉你的老师这是糟糕的设计,在你的Model 中实例化你的View/Controller。应该反过来。看看他/她说了什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多