Advertisement
Zoilorys

Chat Client

Mar 30th, 2015
444
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 11.31 KB | None | 0 0
  1. import java.io.*;
  2. import java.net.Socket;
  3. import java.awt.*;
  4. import java.awt.event.*;
  5.  
  6. import javax.swing.*;
  7. import javax.swing.event.ListSelectionEvent;
  8. import javax.swing.event.ListSelectionListener;
  9.  
  10. import java.text.SimpleDateFormat;
  11. import java.util.*;
  12.  
  13. public class ReworkedChat {
  14.    
  15.     JFrame mainFrame;
  16.     JFrame loginFrame;
  17.     JPanel loginPanel;
  18.     JPanel mainPanel;
  19.     JLabel nameTag;
  20.     JButton loginButton;
  21.     JButton broadcastButton;
  22.    
  23.     JTextField loginText;
  24.     JList<String> userList;
  25.     Vector<String> userVector = new Vector<String>();
  26.    
  27.     ArrayList<DialogWindow> currentDialogs = new ArrayList<DialogWindow>();
  28.     ArrayList<String> currentDialogList = new ArrayList<String>();
  29.     JMenuBar menuBar;
  30.     JMenuItem exitItem;
  31.     JMenu fileMenu;
  32.    
  33.     User currentUser = new User();
  34.     BufferedReader reader;
  35.     PrintWriter writer;
  36.     Socket sock;
  37.     SimpleDateFormat date = new SimpleDateFormat("'('HH:mm:ss')'");
  38.    
  39.  
  40.     public static void main(String[] args) {
  41.        
  42.         new ReworkedChat().go();
  43.  
  44.     }
  45.    
  46.  
  47.     public void go(){
  48.        
  49.         mainFrame = new JFrame("Unicorn Messenger");
  50.         loginFrame = new JFrame("Unicorn Messanger - Log In");
  51.        
  52.         menuBar = new JMenuBar();
  53.         fileMenu = new JMenu("File");
  54.         exitItem = new JMenuItem("Exit");
  55.         exitItem.addActionListener(new ExitListener());
  56.        
  57.         menuBar.add(fileMenu);
  58.         fileMenu.add(exitItem);
  59.        
  60.         mainFrame.setJMenuBar(menuBar);
  61.        
  62.         loginPanel = new JPanel();
  63.         loginPanel.setLayout(new BoxLayout(loginPanel, BoxLayout.Y_AXIS));
  64.        
  65.         mainPanel = new JPanel();
  66.         mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
  67.        
  68.         loginText = new JTextField(15);
  69.         loginText.addKeyListener(new KeyListener(){
  70.            
  71.             public void keyPressed(KeyEvent e) {
  72.                
  73.                  switch(e.getKeyCode()){
  74.                  
  75.                  case KeyEvent.VK_ENTER:
  76.                      
  77.                      if(!loginText.getText().equals("")){
  78.                          
  79.                          logIn();
  80.                          break;
  81.                          
  82.                      }else{
  83.                          
  84.                          break;
  85.                          
  86.                      }
  87.                    
  88.                  }
  89.                      
  90.             }
  91.          
  92.             public void keyReleased(KeyEvent e) {
  93.                          
  94.             }
  95.          
  96.             public void keyTyped(KeyEvent e) {
  97.                          
  98.             }    
  99.         });
  100.         loginPanel.add(loginText);
  101.        
  102.         loginButton = new JButton("Login");
  103.         loginButton.addActionListener(new LoginListener());
  104.         loginPanel.add(loginButton);
  105.        
  106.         nameTag = new JLabel();
  107.         mainPanel.add(nameTag);
  108.                
  109.         broadcastButton = new JButton("Broadcast");
  110.         broadcastButton.addActionListener(new BroadcastListener());
  111.         mainPanel.add(broadcastButton);
  112.        
  113.         userList = new JList<String>();
  114.         userList.addListSelectionListener(new SelectionListener());
  115.         userList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
  116.         JScrollPane list = new JScrollPane(userList);
  117.         userList.setPrototypeCellValue("Index 1234567");
  118.         userList.setListData(userVector);
  119.         mainPanel.add(list);
  120.        
  121.         mainFrame.setContentPane(mainPanel);
  122.         mainFrame.setBounds(500,300,500,500);
  123.         mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  124.         mainFrame.pack();
  125.        
  126.         loginFrame.setContentPane(loginPanel);
  127.         loginFrame.setBounds(500,300,300,100);
  128.         loginFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  129.         loginFrame.setResizable(false);
  130.        
  131.         loginFrame.setVisible(true);
  132.        
  133.     }
  134.    
  135.     public void logIn(){
  136.        
  137.         nameTag.setText(loginText.getText());
  138.         currentUser.setName(loginText.getText());
  139.         loginFrame.setVisible(false);
  140.         mainFrame.setVisible(true);
  141.         setUpNetwork();
  142.        
  143.     }
  144.    
  145.     public void setUpNetwork(){
  146.        
  147.         try{
  148.            
  149.             sock =new Socket("127.0.0.1",5003);
  150.            
  151.             InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());
  152.             reader = new BufferedReader(streamReader);
  153.             writer = new PrintWriter(sock.getOutputStream());
  154.             System.out.println("networking established");
  155.            
  156.         }catch(Exception e){
  157.             e.printStackTrace();
  158.         }
  159.        
  160.         new Thread(new StatusUpdater()).start();
  161.         new Thread(new UserListUpdater()).start();
  162.         new Thread(new IncomingReader()).start();
  163.        
  164.     }
  165.        
  166.     public void send(String message){
  167.        
  168.         try{
  169.            
  170.             writer.println(message);
  171.             writer.flush();
  172.            
  173.         }catch(Exception e ){
  174.             e.printStackTrace();
  175.         }
  176.        
  177.     }
  178.    
  179.     public class LoginListener implements ActionListener{
  180.        
  181.         public void actionPerformed(ActionEvent event){
  182.            
  183.             if(!loginText.getText().equals("")){
  184.                
  185.                 logIn();
  186.                
  187.             }else{
  188.                
  189.                 return;
  190.                
  191.             }
  192.            
  193.         }
  194.     }
  195.    
  196.     public class BroadcastListener implements ActionListener{
  197.        
  198.         public void actionPerformed(ActionEvent event){
  199.            
  200.             if(!currentDialogList.contains("broadcast")){
  201.                
  202.                 DialogWindow window = new DialogWindow();
  203.                 window.init();
  204.                 currentDialogs.add(window);
  205.                 currentDialogList.add(window.getRecipient());
  206.                
  207.             }else{
  208.            
  209.                 currentDialogs.get(currentDialogList.indexOf("broadcast")).setVisible(true);
  210.                
  211.             }
  212.  
  213.         }
  214.     }
  215.    
  216.     public class ExitListener implements ActionListener{
  217.        
  218.         public void actionPerformed(ActionEvent event){
  219.            
  220.             System.exit(0);
  221.            
  222.         }
  223.     }
  224.    
  225.     public class SelectionListener implements ListSelectionListener{
  226.        
  227.         public void valueChanged(ListSelectionEvent event){
  228.            
  229.             if(!event.getValueIsAdjusting()){
  230.                
  231.                 String selection = (String) userList.getSelectedValue();
  232.                
  233.                 if(selection!=null){
  234.                    
  235.                     if(!currentDialogList.contains(selection)){
  236.                        
  237.                         DialogWindow window = new DialogWindow(selection);
  238.                         window.init();
  239.                         currentDialogs.add(window);
  240.                         currentDialogList.add(window.getRecipient());
  241.                        
  242.                     }else{
  243.                    
  244.                         currentDialogs.get(currentDialogList.indexOf(selection)).setVisible(true);
  245.                        
  246.                     }
  247.                    
  248.                 }
  249.                
  250.             }
  251.            
  252.         }
  253.        
  254.     }
  255.  
  256.     public class UserListUpdater implements Runnable{
  257.        
  258.         public void run(){
  259.            
  260.             try{
  261.                
  262.                 while(true){
  263.                    
  264.                     Socket userListSock = new Socket("127.0.0.1", 5005);
  265.                
  266.                     ObjectInputStream is = new ObjectInputStream(userListSock.getInputStream());
  267.                
  268.                     userVector = (Vector<String>) is.readObject();
  269.                     userVector.remove(currentUser.getName());
  270.                     userList.setListData(userVector);
  271.                
  272.                     Thread.sleep(2000);
  273.                    
  274.                 }
  275.                
  276.             }catch(Exception e){e.printStackTrace();}
  277.            
  278.         }
  279.        
  280.     }
  281.    
  282.     public class StatusUpdater implements Runnable{
  283.        
  284.         public void run(){
  285.                
  286.             try{
  287.                    
  288.                     Socket statusSock = new Socket("127.0.0.1",5004);
  289.                
  290.                     ObjectOutputStream os = new ObjectOutputStream(statusSock.getOutputStream());
  291.                     os.writeObject(currentUser);
  292.                        
  293.                     Thread.sleep(2000);
  294.                    
  295.                 }catch(Exception e){e.printStackTrace();}          
  296.             }
  297.            
  298.        
  299.     }
  300.    
  301.     public class IncomingReader implements Runnable{
  302.        
  303.         public void run(){
  304.            
  305.             String message;
  306.            
  307.             try{
  308.                
  309.                 while((message=reader.readLine()) != null){
  310.                    
  311.                     String[] splitted = message.split(":");
  312.                    
  313.                     if(splitted[1].equals("broadcast")){
  314.                        
  315.                         if(!currentDialogList.contains("broadcast")){
  316.                            
  317.                             DialogWindow window = new DialogWindow();
  318.                             window.init();
  319.                             window.incomingMessage(date.format(new Date())+" "+splitted[0]+": "+splitted[2]);
  320.                             currentDialogs.add(window);
  321.                             currentDialogList.add(window.getRecipient());
  322.                            
  323.                         }else{
  324.                        
  325.                             currentDialogs.get(currentDialogList.indexOf("broadcast")).incomingMessage(date.format(new Date())+" "+splitted[0]+": "+splitted[2]);
  326.                             currentDialogs.get(currentDialogList.indexOf("broadcast")).setVisible(true);
  327.                            
  328.                         }
  329.                        
  330.                     }else{
  331.                    
  332.                         if(currentUser.getName().equals(splitted[0])){
  333.                            
  334.                             if(!currentDialogList.contains(splitted[1])){
  335.                                
  336.                                 DialogWindow window = new DialogWindow(splitted[1]);
  337.                                 window.init();
  338.                                 window.incomingMessage(date.format(new Date())+" "+splitted[0]+": "+splitted[2]);
  339.                                 currentDialogs.add(window);
  340.                                 currentDialogList.add(window.getRecipient());
  341.                        
  342.                             }else{
  343.                        
  344.                                 currentDialogs.get(currentDialogList.indexOf(splitted[1])).incomingMessage(date.format(new Date())+" "+splitted[0]+": "+splitted[2]);
  345.                                 currentDialogs.get(currentDialogList.indexOf(splitted[1])).setVisible(true);
  346.                            
  347.                             }
  348.                            
  349.                         }else{
  350.                            
  351.                             if(!currentDialogList.contains(splitted[0])){
  352.                        
  353.                                 DialogWindow window = new DialogWindow(splitted[0]);
  354.                                 window.init();
  355.                                 window.incomingMessage(date.format(new Date())+" "+splitted[0]+": "+splitted[2]);
  356.                                 currentDialogs.add(window);
  357.                                 currentDialogList.add(window.getRecipient());
  358.                        
  359.                             }else{
  360.                        
  361.                                 currentDialogs.get(currentDialogList.indexOf(splitted[0])).incomingMessage(date.format(new Date())+" "+splitted[0]+": "+splitted[2]);
  362.                                 currentDialogs.get(currentDialogList.indexOf(splitted[0])).setVisible(true);
  363.                            
  364.                             }
  365.                         }
  366.                     }
  367.                    
  368.                 }
  369.                
  370.             }catch(Exception e){
  371.                 e.printStackTrace();
  372.             }
  373.            
  374.         }
  375.        
  376.     }
  377.  
  378.     public class DialogWindow{
  379.        
  380.         private String recipient = null;
  381.         private String sender = null;
  382.        
  383.         private JTextArea incoming;
  384.         private JTextField outgoing;
  385.         private JButton sendButton;
  386.         private JFrame messenger;      
  387.        
  388.         public DialogWindow(String reciever){
  389.            
  390.             recipient = reciever;
  391.             sender = currentUser.getName();
  392.            
  393.         }
  394.        
  395.         public DialogWindow(){
  396.            
  397.             recipient = "broadcast";
  398.             sender = currentUser.getName();
  399.            
  400.         }
  401.        
  402.         public void incomingMessage(String message){
  403.            
  404.             incoming.append(message+"\n");
  405.             messenger.setVisible(true);
  406.            
  407.         }
  408.        
  409.         public void setVisible(boolean state){
  410.            
  411.             messenger.setVisible(state);
  412.            
  413.         }
  414.        
  415.         public String getRecipient(){
  416.            
  417.             return recipient;
  418.            
  419.         }
  420.        
  421.         public void init(){
  422.            
  423.             messenger = new JFrame("Chat - "+recipient);
  424.             messenger.setBounds(450,300,400,300);
  425.             messenger.setResizable(false);
  426.             messenger.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);      
  427.            
  428.             JPanel panel = new JPanel();
  429.            
  430.             incoming = new JTextArea(15,32);
  431.             incoming.setLineWrap(true);
  432.             incoming.setWrapStyleWord(true);
  433.             incoming.setEditable(false);       
  434.            
  435.             JScrollPane scroller = new JScrollPane(incoming);
  436.             scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
  437.             scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
  438.            
  439.             outgoing = new JTextField(25);
  440.             outgoing.addKeyListener(new KeyListener(){
  441.                
  442.                 public void keyPressed(KeyEvent e) {
  443.                    
  444.                      switch(e.getKeyCode()){
  445.                      
  446.                      case KeyEvent.VK_ENTER:
  447.                          
  448.                          send(sender+":"+recipient+":"+outgoing.getText());
  449.                          outgoing.setText("");
  450.                          outgoing.requestFocus();
  451.                          break;
  452.                        
  453.                      }
  454.                          
  455.                 }
  456.              
  457.                 public void keyReleased(KeyEvent e) {
  458.                              
  459.                 }
  460.              
  461.                 public void keyTyped(KeyEvent e) {
  462.                              
  463.                 }    
  464.             });
  465.            
  466.             sendButton = new JButton("Send");
  467.             sendButton.addActionListener(new SendListener());
  468.            
  469.             panel.add(outgoing);
  470.             panel.add(sendButton);
  471.            
  472.             messenger.getContentPane().add(scroller, BorderLayout.CENTER);
  473.             messenger.getContentPane().add(panel, BorderLayout.SOUTH);
  474.            
  475.             messenger.setVisible(true);
  476.             outgoing.requestFocus();
  477.            
  478.         }
  479.        
  480.         public class SendListener implements ActionListener{
  481.            
  482.             public void actionPerformed(ActionEvent event){
  483.                
  484.                 send(sender+":"+recipient+":"+outgoing.getText());
  485.                 outgoing.setText("");
  486.                 outgoing.requestFocus();
  487.                
  488.             }
  489.            
  490.         }
  491.        
  492.     }
  493. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement