There is a first class in which I want to transfer data from the second class.
public class Client extends UserInterfaceClient { private PrintWriter writer; Socket socket; public void setUpConnection (){ TestActionListener testActionListener = new TestActionListener(); try { socket = new Socket("127.0.0.1", 5052); writer = new PrintWriter(socket.getOutputStream(),true); writer.println(testActionListener.getMessages()); System.out.print(testActionListener.getMessages()); writer.flush(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } And here is the second class from which I'm trying to convey the value.
public class UserInterfaceClient { JTextField outgoing; JTextField test; public void go(){ JFrame frame = new JFrame("Client"); JPanel mainPanel = new JPanel(); outgoing = new JTextField(20); test = new JTextField(10); JButton sendButton = new JButton("Send"); ActionListener actionListener = new TestActionListener(); frame.getContentPane().add(BorderLayout.CENTER, mainPanel); frame.setSize(400, 500); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setVisible(true); mainPanel.add(sendButton); mainPanel.add(outgoing); sendButton.addActionListener(actionListener); } public class TestActionListener implements ActionListener{ private String messages; @Override public void actionPerformed(ActionEvent e) { try { messages = outgoing.getText(); }catch (Exception ex){ ex.printStackTrace(); } outgoing.setText(""); outgoing.requestFocus(); } public String getMessages(){ return messages; } } public static void main (String[] args){ new UserInterfaceClient().go(); new Client().setUpConnection(); } } I understand that before clicking the button, the TestActionListener messages class field is null. As a result, it is this value that is passed through the method to another class. Why is that?