【问题标题】:How to transfer String from one class to another in Java如何在 Java 中将字符串从一个类转移到另一个类
【发布时间】:2015-06-24 12:06:18
【问题描述】:

我有这两个类:

ConnectionPanel.class

public class ConnectionPanel extends JPanel implements ActionListener,ItemListener, PropertyChangeListener {
   private MasterModel m_masterModel;
   private JTextField m_keyField;

   public ConnectionPanel(MasterModel masterModel) {
       m_masterModel = masterModel;
       setLayout(new GridLayout(0, 2));
       JPanel panel = null;
       panel = new JPanel();
       panel.add(new JLabel("Type Key:"));
       m_keyField = new JTextField(9);
       m_keyField.setText("dertfgdertabcdef");
       panel.add(m_keyField);
       add(panel);
       getChatModel().addPropertyChangeListener(this);
       getChatModel().setListen(true);
    } 

    public String getEncryptionKey(){
       return m_keyField.getText();
    }
}

AudioPlayback.class

public class AudioPlayback extends AudioBase {
    // and here I want to be able to get
    // somehow String key = ConnectionPanel.getEncryptionKey()
    // I tried ConnectionPanel panel = new ConnectionPanel(); but does not work
    // it messes my graphical interface
    // also there is lots of code here too
}

您有什么想法可以让我将该字段输入到我的 audioplayback.class 中吗?

【问题讨论】:

  • 你了解Java中类、变量和关键字的基础知识吗?
  • 我很少使用多个类,我的大多数应用程序都是程序化的,这就是我遇到这个问题的原因。
  • 如果你想用它做一个应用程序,我建议看看一些关于如何使用类的教程。
  • 我第二个 @moffeltje - 这是一个非常基本的 java 语法/OO 设计问题,可能不适合堆栈溢出。在这种情况下,您的 AudioPlayback 需要获取参考 ConnectoinPanel
  • 对不起,我知道这个问题可能很简单,但我什至不知道在哪里寻找答案。如果您能建议任何链接以找到此问题的答案,我将不胜感激。

标签: java string class


【解决方案1】:

我完全同意 moffeltje & Luke 的观点。这个问题很简单,所以我认为你可以学习一些关于 Java 的更基础的东西。 但是我查看了您的 ConnectionPanel 构造函数。请问,您知道构造函数吗? 您可以在此处找到详细信息: https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

现在,让我们谈谈您的代码。您只给 ConnectionPanel 一个输入参数的构造函数,这样您就不能在 AudioPlayback 中使用没有参数的构造函数。 但是你的 ConnectionPanel 中似乎没有调用 masterModel 属性,所以你可以大致使用以下代码:

// Notice! Don't do this in your production enviroment. It's only for test otherwise you can make sure that you can give the null value to it.
ConnectionPanel panle = new ConnectionPanel(null);
System.out.println(panel.getEncryptionKey());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-10
    • 2017-03-25
    • 1970-01-01
    • 2018-10-29
    相关资源
    最近更新 更多