2012-12-23 3 views
2

Jlabel, JTextArea를 코드에서 업데이트하는 데 문제가 있습니다. 그러나 작동하지 않습니다.Runnable.run 메서드에서 스윙 구성 요소를 업데이트 할 수 없습니다.

Explaination :

내가 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("[email protected]!"+ 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] 
        + " [email protected][email protected]!"+"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("[email protected][email protected]!" + decodedFromClient[0] 
       + " left chat room @[email protected]!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] +"@!"[email protected]!" + 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 @! [email protected]! type of msg"; 
      os.println(uname + " @! server @! " + uname + " @! iamonline");//@[email protected]! 
      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); 
     } 
    } 
} 

먼저 '은'사용자 이름과 'A'암호 required.I 생각하면이 아닌 나의 일 기준 사촌 작동하지 않습니다로 welcomescreen.sign 실행하십시오 Multithreadchatserver 클래스를 실행하고 귀하의 컴퓨터에.

ClientGui.java의 코드에서 JTextArea 및 JLabel을 업데이트 할 수없는 이유를 말씀해주십시오. 320 및 321. 나는 정말 어떤 도움을 주셔서 감사하겠습니다. 미리 감사드립니다. 하나님 께서 당신을 축복 해 주실 것입니다.

+0

잘못된 서식에 대해 죄송합니다. 링크와 코드의 서식을 지정할 수 없습니다. 두 개 이상의 링크를 입력 할 수 없습니다. –

+1

[Concurency in Swing] (http : // docs. oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html) 더 나은 도움을 받으려면 [SSCCE] (http://sscce.org/), 짧은 실행 파일, 컴파일 가능한, 단지'JLabel' ,'JTextArea' 그리고'/ Socket'에서/msgs를 가져오고/가져 오십시오. – mKorbel

+0

@mKorbel 미안합니다.하지만 당신의 도움을 이해할 수 없습니다. SSCCE에 대해서 같은 질문을해야합니다. 질문에 SSCCE.can 코드 320 라인 321에서 내 실수를 지적했다. –

답변

2

문제는 ClientGUI 클래스에 있습니다.

라인 193 :

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

귀하의 코드는 아직 오히려 ClientGUI보다, 눈에 보이지 않는이었다 새로운 ClientGUI의, 동부 서머 타임에 UI 구성 요소를 업데이트하고 제대로 않았다

new Thread(this).start() 

해야한다 그것은 이미 보여주고있었습니다.

+0

고마워요 @ 보우 모어. 내 문제가 해결되었습니다. 내가 너에게 경의를 표한다. –