我有一个关于从代码更新Jlabel,JTextArea的问题。但是它不起作用。

说明:

我有3节课

package chatgui4;
//worked on it
import java.io.DataInputStream;
import java.io.PrintStream;
import java.io.IOException;
import java.net.Socket;
import java.net.ServerSocket;

public class MultiThreadChatServer {

  private static ServerSocket serverSocket = null;
  private static Socket clientSocket = null;

  // This chat server can accept up to maxClientsCount clients' connections.
  private static final int maxClientsCount = 10;
  private static final clientThread[] threads = new clientThread[maxClientsCount];

  public static void main(String args[]) {

    int portNumber = 2222;

    try {
      serverSocket = new ServerSocket(portNumber);
      System.out.println("Server Started at port: 2222");
    } catch (IOException e) {
      System.out.println(e);
    }

    // Create a client socket for each connection and pass it to a new client thread
    while (true) {
      try {
        clientSocket = serverSocket.accept();
        int i ;
        for (i = 0; i < maxClientsCount; i++) {
          if (threads[i] == null) {
            (threads[i] = new clientThread(clientSocket, threads)).start();
            break;
          }
        }
      } catch (IOException e) {
        System.out.println(e);
      }//end catch
    }//end while
  }//end main
}//end public class MultiThreadChatServer

class clientThread extends Thread {

  private DataInputStream is = null;
  private PrintStream os = null;
  private Socket clientSocket = null;
  private final clientThread[] threads;
  private int maxClientsCount;
  private  String fromClient;
  boolean closed=false;

  public clientThread(Socket clientSocket, clientThread[] threads) {
    this.clientSocket = clientSocket;
    this.threads = threads;
    maxClientsCount = threads.length;
  }

  public void run() {
   // maxClientsCount = this.maxClientsCount;
    clientThread[] threads = this.threads;

    try {
      is = new DataInputStream(clientSocket.getInputStream());
      os = new PrintStream(clientSocket.getOutputStream());
      while(!is.readLine().isEmpty()){

       fromClient = is.readLine().trim();
       //System.out.println(fromClient);
       String[] decodedFromClient=fromClient.split("@!");

       if(decodedFromClient[1].trim().equals("server")){
         if (decodedFromClient[3].trim().equals("iamonline")){
            System.out.println(decodedFromClient[0]+ " connected.");
            os.println("Server@!"+ decodedFromClient[0]+"@!Hello " + decodedFromClient[0]+ "@!all");

            for (int i = 0; i < maxClientsCount; i++) {
                if (threads[i] != null && threads[i] != this) {
                threads[i].os.println("User " + decodedFromClient[0]
                    + " entered.@!populateOnline@!"+"decodedFromClient[0]");
                }
            }
            }//end if iamonline
        else if(decodedFromClient[3].trim().equals("quit")){
           for (int i = 0; i < maxClientsCount; i++) {
            if (threads[i] != null && threads[i] != this) {
                threads[i].os.println("server@!all@!" + decodedFromClient[0]
                + " left chat room @!removeOnline@!decodedFromClient[0]");
          //from @! to @! msg @! work @! extra/whom==5
        }
      }
       }

       }//end if to server

       else {
      //while (true) {
        //String line = is.readLine();
        //String[] decodedLine=line.split("@!");
        for (int i = 0; i < maxClientsCount; i++) {
          if (threads[i] != null) {
            //threads[i].os.println(decodedFromClient[0]+"@!"+decodedFromClient[1] +"@!"+chatMsg@!" +  decodedFromClient[0]+": " + line);
              System.out.println(fromClient);
              threads[i].os.println(fromClient);
          }
        }
      //}
       }//end else if not server
}

      /*temp coment
      is.close();
      os.close();
      clientSocket.close();
      */
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }
//}//close while
  }
}

iii。 ClientGUI.java

软件包chatgui4;
import java.awt.EventQueue;
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

/**
 *
 * @author sulav
 */
public class ClientGUI extends javax.swing.JFrame implements Runnable {

    /**
     * Creates new form ClientGUI
     */
    private static Socket clientSocket = null;
    // The output stream
    private static PrintStream os = null;
    // The input stream
    private static DataInputStream is = null;
    private static BufferedReader inputLine = null;
    private static boolean closed = false;
    public static String uname;

    public ClientGUI() {
        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();
        jTextArea1 = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jButton3 = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        jList2 = new javax.swing.JList();
        jLabel3 = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

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

        jLabel1.setText("Online Users");

        jLabel2.setText("Terminal");

        jButton1.setText("Connect");
        jButton1.setMargin(new java.awt.Insets(2, 2, 2, 2));
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Disconnect");
        jButton2.setMargin(new java.awt.Insets(2, 2, 2, 2));

        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });

        jButton3.setText("Send");
        jButton3.setMargin(new java.awt.Insets(2, 2, 2, 2));
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jList2.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "ram", "a", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane3.setViewportView(jList2);

        jLabel3.setText("jLabel3");

        jMenu1.setText("File");
        jMenuBar1.add(jMenu1);

        jMenu2.setText("Availability");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 269, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(24, 24, 24)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 343, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(20, 20, 20)
                                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(7, 7, 7)
                        .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(230, 230, 230)
                        .addComponent(jButton1)
                        .addGap(11, 11, 11)
                        .addComponent(jButton2)))
                .addContainerGap(28, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(5, 5, 5)
                        .addComponent(jLabel2)))
                .addGap(7, 7, 7)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(6, 6, 6)
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(36, 36, 36)
                        .addComponent(jButton3))
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(15, 15, 15)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(23, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-491)/2, (screenSize.height-381)/2, 491, 381);
    }// </editor-fold>

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        int portNumber = 2222;
        String host = "localhost";
        try {
            clientSocket = new Socket(host, portNumber);
           // System.out.println(clientSocket);
            System.out.println("connected");
            inputLine = new BufferedReader(new InputStreamReader(System.in));
            os = new PrintStream(clientSocket.getOutputStream());
            is = new DataInputStream(clientSocket.getInputStream());
            //"from @! to @! message@! type of msg";
            os.println(uname + " @! server @! " + uname + " @! iamonline");//@!@!
            this.setTitle("Talk to me: "+uname);

        } catch (UnknownHostException e) {
            System.err.println("Don't know about host " + host);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to the host "+ host);
        }


        if (clientSocket != null && os != null && is != null) {
            try {

              new Thread(new ClientGUI()).start();

            } catch (Exception e) {
                System.err.println("IOException:  " + e);
            }
        }
    }

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
        String typeMsg = jTextField1.getText();//@!
        String selected = jList2.getSelectedValue().toString();
        //System.out.print("msg sent to: "+selected+" "+typeMsg);
        //os.println(uname + "@!" + selected + "@!" + typeMsg + "@!msg");
        String Quit="quit";
        //System.out.println(selected);
        if(Quit.equalsIgnoreCase(typeMsg.trim()))
        {os.println(uname + "@!" + selected + "@!" + typeMsg + "@!quit");
        System.out.print("oi quit vo re");
        jTextArea1.append(typeMsg);
        }
        else{
        os.println(uname + "@!" + selected + "@!" + typeMsg + "@!msg");
        //System.out.print("msg sent to: "+selected+" "+typeMsg);
        jTextArea1.append(typeMsg+"\n");
        }
        jTextField1.setText("");
    }

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
        String typeMsg = jTextField1.getText();//@!
        String selected = jList2.getSelectedValue().toString();
        String Quit="quit";
        //System.out.println(selected);
        if(Quit.equalsIgnoreCase(typeMsg.trim()))
        {os.println(uname + "@!" + selected + "@!" + typeMsg + "@!quit");
        System.out.print("oi quit vo re");
        jTextArea1.append(typeMsg);
        }
        else{
        os.println(uname + "@!" + selected + "@!" + typeMsg + "@!msg");
       // System.out.print("msg sent to: "+selected+" "+typeMsg);
        jTextArea1.append(typeMsg+"\n");
        }
        jTextField1.setText("");
    }

    public static void main(String args[]) {

         System.out.println("lau main() vitra po chirecha ta.achamma hai:0)");

        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ClientGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ClientGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ClientGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ClientGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ClientGUI().setVisible(true);
                System.out.println("lau yo ni printed lol");

            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JList jList2;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration
String responseLine;
    @Override
    public  void run() {
        /*
         * Keep on reading from the socket till we receive "Bye" from the
         * server. Once we received that then we want to break.
         */
        System.out.println("aba yo print vayo hai");
//        String responseLine;
        try {
            while ((responseLine = is.readLine().trim()) != null) {
                String[] decodedResponseLine = responseLine.split("@!");

                if (decodedResponseLine.length == 4) {
                    if (decodedResponseLine[1].trim().equals(uname)) {
                        System.out.println("jkjlkjkljjjjjjjjjj"+java.awt.EventQueue.isDispatchThread());
                        jTextArea1.setText("aayooooooooo hai");
                        jLabel3.setText(decodedResponseLine[2].toString().trim());

                    }
                } else if (decodedResponseLine.length == 3) {
                    //jList1.
                } else if (decodedResponseLine.length == 5) {
                }

                java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                System.out.println("EDT running here "+java.awt.EventQueue.isDispatchThread());
                System.out.println("from invokelater");
                jTextArea1.append(responseLine);
                jLabel3.setText("suleman");
            }
        });
                System.out.println("jkjlkjkl"+java.awt.EventQueue.isDispatchThread());



                if (responseLine.indexOf("*** Bye") != -1) {
                    break;
                }
            }
            closed = true;
        } catch (IOException e) {
            System.err.println("IOException:  " + e);
        }
    }
}

首先运行Multithreadchatserver类,然后运行welcomescreen。如果需要,请使用“a”用户名和“a”密码登录。我认为这行不通,因为我的日期基于不在您的计算机中。

您能否告诉我,为什么我不能从ClientGui.java行号中的代码更新JTextArea和JLabel。 320和321。我将非常感谢您的帮助。
提前致谢。
上帝会保佑你。

最佳答案

问题出在ClientGUI类中。

第193行:

new Thread(new ClientGUI()).start()

应该
new Thread(this).start()

您的代码确实更新了UI组件,并且正确地在EDT上更新了新的ClientGUI(它是不可见的),而不是已经显示的ClientGUI。

10-04 11:32