icorrelate

ChatApp.java

Nov 29th, 2016
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 9.96 KB | None | 0 0
  1. import java.awt.BorderLayout;
  2. import java.awt.Dimension;
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;
  5. import java.awt.event.KeyEvent;
  6. import java.awt.event.WindowEvent;
  7. import java.awt.event.WindowListener;
  8. import java.io.BufferedReader;
  9. import java.io.File;
  10. import java.io.FileNotFoundException;
  11. import java.io.FileReader;
  12. import java.io.FileWriter;
  13. import java.io.IOException;
  14. import java.net.InetAddress;
  15. import java.net.UnknownHostException;
  16. import javax.swing.JFrame;
  17. import javax.swing.SwingUtilities;
  18. import javax.swing.filechooser.FileNameExtensionFilter;
  19. import javax.swing.*;
  20.  
  21.  
  22.  
  23. public class ChatApp extends JFrame{
  24.     private String path = "";
  25.     private final int interval = 1500;
  26.    
  27.     private JButton btnsend;
  28.     private JTextField txtmessage;
  29.     private JTextArea txtChats;
  30.    
  31.     private String name = "";
  32.     private String tempname = "";
  33.     private String computerName;
  34.     private final int FRAME_WIDTH = 640;
  35.     private final int FRAME_HEIGHT = 480;
  36.  
  37.     private InetAddress localMachine;
  38.     private Timer timer;
  39.    
  40.     public ChatApp(){
  41.         //Frame Title
  42.         super("Chat Application");
  43.         //Frame Size
  44.         setSize(FRAME_WIDTH,FRAME_HEIGHT);
  45.         //Put the frame on center
  46.         setLocationRelativeTo(null);
  47.        
  48.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  49.        
  50.         //Sets computer name and ask for user name
  51.         computerName = getComputerName();
  52.         changeName();
  53.        
  54.        
  55.         //*******MENU BAR **************//
  56.         final JMenuBar menuBar = new JMenuBar();
  57.        
  58.         //======Creating "File" Menu====//
  59.         JMenu fileMenu = new JMenu("File");
  60.         JMenuItem exitMenuItem = new JMenuItem("Exit");
  61.         exitMenuItem.setMnemonic(KeyEvent.VK_X);
  62.         exitMenuItem.addActionListener(new ActionListener() {
  63.             @Override
  64.             public void actionPerformed(ActionEvent e) {
  65.                 System.exit(0);
  66.             }
  67.         });
  68.         fileMenu.add(exitMenuItem);
  69.         //===============================//
  70.          
  71.          
  72.         //======Creating "Edit" Menu====//
  73.        
  74.         JMenu editMenu = new JMenu("Edit");
  75.        
  76.                         //For Changing name//
  77.         JMenuItem changeMenuItem = new JMenuItem("Change Name");
  78.         changeMenuItem.setMnemonic(KeyEvent.VK_C);
  79.         changeMenuItem.addActionListener(new ActionListener() {
  80.             @Override
  81.             public void actionPerformed(ActionEvent e) {
  82.                 tempname = name;
  83.                 name = "";
  84.                 changeName();
  85.             }
  86.         });
  87.         editMenu.add(changeMenuItem);
  88.        
  89.        
  90.        
  91.         JMenuItem chPathMenuItem = new JMenuItem("Change Path of Logs");
  92.         chPathMenuItem.setMnemonic(KeyEvent.VK_L);
  93.         chPathMenuItem.addActionListener(new ActionListener() {
  94.             @Override
  95.             public void actionPerformed(ActionEvent e) {
  96.                 changePath();
  97.             }
  98.         });
  99.         editMenu.add(chPathMenuItem);
  100.        
  101.        
  102.         //===============================//
  103.        
  104.         //Adding Menus to MenuBar and setting the MenuBar
  105.         menuBar.add(fileMenu);
  106.         menuBar.add(editMenu);
  107.         setJMenuBar(menuBar);
  108.         //*******MENU BAR **************//
  109.        
  110.        
  111.          
  112.          
  113.        
  114.         txtmessage = new JTextField();
  115.         txtmessage.setPreferredSize(new Dimension(400, 20));
  116.         txtChats = new JTextArea();
  117.         txtChats.setEditable(false);
  118.        
  119.         //Change TextArea font to 14;
  120.         txtChats.setFont(txtChats.getFont().deriveFont(14f));
  121.        
  122.         //If message is too long, continue it to the next line.
  123.         txtChats.setLineWrap(true);
  124.         txtChats.setWrapStyleWord(true);
  125.        
  126.        
  127.         //Add Vertical Scroll bars to our text area.
  128.         JScrollPane scroll = new JScrollPane (txtChats);
  129.         scroll.setVerticalScrollBarPolicy ( ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS );
  130.        
  131.        
  132.         //Write to text file then read the logs
  133.         btnsend = new JButton("Send");
  134.         btnsend.addActionListener(new ActionListener() {
  135.             @Override
  136.             public void actionPerformed(ActionEvent e) {
  137.                 writeToChatLogs(String.format("[%s: %s] %s", computerName, name,  txtmessage.getText()));
  138.                 readChatLogs();
  139.                 txtmessage.setText("");
  140.             }
  141.         });
  142.        
  143.        
  144.         //Adding our components to the panels
  145.         JPanel mainPanel = new JPanel();
  146.         mainPanel.setLayout(new BorderLayout());
  147.         mainPanel.add(scroll, BorderLayout.CENTER);
  148.        
  149.         JPanel southPanel = new JPanel();
  150.         southPanel.add(txtmessage);
  151.         southPanel.add(btnsend);
  152.         mainPanel.add(southPanel, BorderLayout.SOUTH);
  153.        
  154.         setContentPane(mainPanel);
  155.        
  156.        
  157.         //Timer Declaration. Timer execute task (Reading logs) on set interval.
  158.         timer = new Timer(interval, new ActionListener() {
  159.               @Override
  160.               public void actionPerformed(ActionEvent arg0) {
  161.                 readChatLogs();
  162.               }
  163.             });
  164.         timer.setRepeats(true);
  165.        
  166.         //Start the timer
  167.         timer.start();
  168.        
  169.         //Focus cursor to text box message
  170.         txtmessage.requestFocus();
  171.        
  172.         //Adding a "Default Key" so you just need to hit enter to send
  173.         JRootPane rootPane = SwingUtilities.getRootPane(btnsend);
  174.         rootPane.setDefaultButton(btnsend);
  175.        
  176.        
  177.        
  178.         //========Window Listener=======//
  179.         addWindowListener(new WindowListener() {
  180.             @Override
  181.             public void windowOpened(WindowEvent e) {
  182.                
  183.             }
  184.            
  185.             @Override
  186.             public void windowIconified(WindowEvent e) {
  187.                 //If Frame is minimized, write [Computer Name: Username] is idle!; or tell other user that you are idle
  188.                 if(fileExist()){
  189.                     writeToChatLogs("\t\tUser: " + String.format("[%s: %s] %s", computerName, name, " is Idle!"));
  190.                 }
  191.                 //You can stop the timer that reads the chat logs here if you want since it does not make sense to refresh the logs if the user does not see it.
  192.                 if(timer.isRunning()){
  193.                     timer.stop();
  194.                 }
  195.             }
  196.            
  197.             @Override
  198.             public void windowDeiconified(WindowEvent e) {}
  199.             @Override
  200.             public void windowDeactivated(WindowEvent e) {
  201.                 //Tells other user if he / she is idle when you navigated away from the frame.
  202.                 if(fileExist())
  203.                     if(name.equals(""))     //if the user is changing his name.
  204.                         writeToChatLogs("\t\tUser: " + String.format("[%s: %s] %s", computerName, tempname, " is Idle!"));
  205.                     else
  206.                         writeToChatLogs("\t\tUser: " + String.format("[%s: %s] %s", computerName, name, " is Idle!"));
  207.             }
  208.            
  209.             @Override
  210.             public void windowClosing(WindowEvent e) {
  211.                 //Ask the user if he / she wants to exit.
  212.                 if (JOptionPane.showConfirmDialog(null, "Are you sure you want to Exit", "Leave?", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) {
  213.                     return;
  214.                 }else{
  215.                     if(fileExist())
  216.                     writeToChatLogs("\t\tUser: " + String.format("[%s: %s] %s", computerName, name, " left the conversation!"));
  217.                     System.exit(0);
  218.                 }
  219.             }
  220.            
  221.             @Override
  222.             public void windowClosed(WindowEvent e) {}
  223.            
  224.             @Override
  225.             public void windowActivated(WindowEvent e) {
  226.                 //Notify other user if the he / she is active or is in the frame.
  227.                 if(fileExist())
  228.                 writeToChatLogs("\t\tUser: " + String.format("[%s: %s] %s", computerName, name, " is now Active!"));
  229.                
  230.                 //If timer timer is stopped because the user minimize the app, start it .
  231.                 if(!timer.isRunning()){
  232.                     timer.start();
  233.                 }
  234.                
  235.             }
  236.         });
  237.         //==============================//
  238.        
  239.        
  240.         //Show the Frame or Window
  241.         setVisible(true);
  242.        
  243.     }
  244.    
  245.     //IF the current path is not set or is invalid, you will be asked to find the txt file in your network.
  246.     public void changePath(){
  247.         try {
  248.             JFileChooser fc = new JFileChooser();
  249.             fc.addChoosableFileFilter(new FileNameExtensionFilter("Text File", "txt"));
  250.             int returnVal = fc.showOpenDialog(this);
  251.  
  252.             if (returnVal == JFileChooser.APPROVE_OPTION) {
  253.                 File file = fc.getSelectedFile();
  254.                 String newPath = file.getAbsolutePath();
  255.                 path = newPath;
  256.                 JOptionPane.showMessageDialog(this, "Path set by user to ." + newPath);
  257.             } else {
  258.                 JOptionPane.showMessageDialog(this, "Open command cancelled by user." );
  259.             }
  260.         } catch (Exception e) {
  261.             e.printStackTrace();
  262.         }
  263.     }
  264.    
  265.     //This block of code is used to change the name of the user
  266.     public void changeName(){
  267.         try {
  268.             while(name.length() < 4l){
  269.                 name = JOptionPane.showInputDialog(this, "Enter your name: ");
  270.                 if(name.length() < 4){
  271.                     JOptionPane.showMessageDialog(this, "Minimum of 4 characters required!");
  272.                 }
  273.             }
  274.         } catch (Exception e) {
  275.             if(tempname.equals("") || tempname == null){
  276.                 name = "Anonymous";
  277.             }
  278.             else
  279.             {
  280.                 name = tempname;
  281.             }
  282.         }
  283.     }
  284.     //This method gets the name of the computer and return it.
  285.     public String getComputerName(){
  286.         try {
  287.             localMachine = InetAddress.getLocalHost();
  288.         } catch (UnknownHostException e) {
  289.             e.printStackTrace();
  290.         }
  291.         return localMachine.getHostName();
  292.     }
  293.    
  294.     //This block of code is responsible for writting the message to chat logs.
  295.     public void writeToChatLogs(String message){
  296.         try {
  297.             FileWriter mywriter = new FileWriter(path, true);
  298.             mywriter.append("\n" + message);
  299.             mywriter.close();
  300.         } catch (IOException e) {
  301.             e.printStackTrace();
  302.         }
  303.     }
  304.    
  305.    
  306.     //Shows an error if the txt file is not found or is deleted.
  307.     public void checkIfFileExist()
  308.     {
  309.         if(!fileExist()){
  310.             JOptionPane.showMessageDialog(this,
  311.                     "Please select a chat log txt file.",
  312.                     "File Not Found",
  313.                     JOptionPane.ERROR_MESSAGE);
  314.             changePath();
  315.         }
  316.     }
  317.    
  318.     //Check if file exist
  319.     public boolean fileExist(){
  320.         File chatfile = new File(path);
  321.         return chatfile.exists();
  322.     }
  323.    
  324.    
  325.     //Responsible for reading the chat logs and appending it to the JTextArea
  326.     public void readChatLogs()
  327.     {
  328.         checkIfFileExist();
  329.         txtChats.setText("");
  330.         try {
  331.             FileReader reader = new FileReader(path);
  332.             BufferedReader br = new BufferedReader(reader);
  333.             String line;
  334.            
  335.             while((line = br.readLine()) != null){
  336.                 txtChats.append("\n" + line);
  337.             }
  338.             br.close();
  339.         } catch (FileNotFoundException e) {
  340.             checkIfFileExist();
  341.             e.printStackTrace();
  342.         } catch (IOException e) {
  343.             e.printStackTrace();
  344.         }
  345.     }
  346.    
  347.     public static void main(String[] args) {
  348.         //Running the app in a thread safe manner.
  349.           SwingUtilities.invokeLater(new Runnable() {
  350.              @Override
  351.              public void run() {
  352.                 new ChatApp();
  353.              }
  354.           });
  355.     }
  356. }
Add Comment
Please, Sign In to add comment