将变量值从一个类传递到另一个Java

时间:2016-12-05 23:53:08

标签: java class dialog

如何在不创建新对象实例的情况下将变量值从一个类传递到另一个类? 基本上,我有这些客户端和服务器类,我想将客户端用户名值传输到服务器类,因此可以在“sendToAll”服务器方法中识别每个用户。

客户端类:

id

服务器类:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package chat;

import java.io.*;
import java.net.*;
import javax.swing.JOptionPane;

/**
 *
 * @author Allura
 */
public class ChatClient extends javax.swing.JFrame {
    BufferedReader reader;
    PrintWriter writer;
    String username;
    /**
     * Creates new form ChatClient
     */
    public ChatClient() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        messageBox = new javax.swing.JTextArea();
        inputBox = new javax.swing.JTextField();
        sendButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        messageBox.setEditable(false);
        messageBox.setColumns(20);
        messageBox.setRows(5);
        jScrollPane1.setViewportView(messageBox);

        sendButton.setText("Send");
        sendButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(inputBox, javax.swing.GroupLayout.PREFERRED_SIZE, 462, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(sendButton, javax.swing.GroupLayout.DEFAULT_SIZE, 118, Short.MAX_VALUE))
                    .addComponent(jScrollPane1))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 353, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(inputBox)
                    .addComponent(sendButton, javax.swing.GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE))
                .addContainerGap(23, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
        if(!inputBox.getText().equals(""))
        {
            try
            {
                writer.println(inputBox.getText());
                writer.flush();
            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }
        }
    }                                          

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        ChatClient client = new ChatClient();
        client.go();
    }
    public void go()
    {
        username = JOptionPane.showInputDialog(this, "Enter a username: ");
        setUpNetwork();
        setVisible(true);
        Thread myRunner = new Thread(new MessageReader());
        myRunner.start();
    }
    public void setUpNetwork()
    {
        try
        {
            Socket sock = new Socket("0.0.0.0", 5000);
            InputStreamReader input = new InputStreamReader(sock.getInputStream());
            reader = new BufferedReader(input);
            writer = new PrintWriter(sock.getOutputStream());
            System.out.println("Connection established.");
        }
        catch(IOException ex)
        {
            ex.printStackTrace();
        }
    }
    public class MessageReader implements Runnable
    {
        String message;
        public void run()
        {
            try
            {
                while ((message = reader.readLine()) != null)
                {
                    messageBox.append(message + "\n");
                }
            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }
        }
    }
    // Variables declaration - do not modify                     
    private javax.swing.JTextField inputBox;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea messageBox;
    private javax.swing.JButton sendButton;
    // End of variables declaration                   
}

1 个答案:

答案 0 :(得分:0)

由于您正在处理通过套接字进行通信的两个不同进程(客户端和服务器),因此无法阻止创建新对象。

我认为标题和问题描述有点误导。