如何在Java中将String从一个类传递到另一个类

时间:2015-06-24 12:06:18

标签: java string class

我有这两个类:

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中?

1 个答案:

答案 0 :(得分:0)

我完全赞同moffeltje&卢克。这个问题很简单,所以我认为你可以学习更基础的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());