Advertisement
Guest User

ClientGUI.java

a guest
Oct 21st, 2014
297
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 8.01 KB | None | 0 0
  1. import javax.swing.JFrame;
  2. import javax.swing.JPanel;
  3. import java.awt.SystemColor;
  4. import javax.swing.ButtonGroup;
  5. import javax.swing.JTextArea;
  6. import javax.swing.JTextField;
  7. import javax.swing.JLabel;
  8. import javax.swing.JRadioButton;
  9. import javax.swing.SwingUtilities;
  10. import java.awt.Toolkit;
  11. import javax.swing.JButton;
  12. import java.awt.event.ActionListener;
  13. import java.awt.event.ActionEvent;
  14. import java.io.EOFException;
  15. import java.io.IOException;
  16. import java.io.ObjectInputStream;
  17. import java.io.ObjectOutputStream;
  18. import java.net.Socket;
  19.  
  20. public class ClientGUI extends JFrame {
  21.  
  22.     private static final long serialVersionUID = 1L;
  23.     private JFrame frame;
  24.     private JTextField enterField;
  25.     private JTextField txtServerIP;
  26.     private JTextField txtServerPort;
  27.     private JTextArea displayArea;
  28.     public String clientNick = "";
  29.  
  30.     private ObjectOutputStream output;
  31.     private ObjectInputStream input;
  32.     private String message = "";
  33.     private String chatServer;
  34.     private Socket client;
  35.  
  36.     private final ButtonGroup buttonGroup = new ButtonGroup();
  37.  
  38.     /**
  39.      * Launch the application.
  40.      */
  41.  
  42.     public ClientGUI(String host) {
  43.         super("Client Interface");
  44.         chatServer = host;
  45.         initialize();
  46.  
  47.     }
  48.  
  49.     /**
  50.      * Initialize the contents of the frame.
  51.      */
  52.     private void initialize() {
  53.         frame = new JFrame();
  54.         frame.setIconImage(Toolkit
  55.                 .getDefaultToolkit()
  56.                 .getImage(
  57.                         ClientGUI.class
  58.                                 .getResource("/com/sun/java/swing/plaf/windows/icons/Computer.gif")));
  59.         frame.setBounds(100, 100, 640, 589);
  60.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  61.         frame.getContentPane().setLayout(null);
  62.  
  63.         JPanel panel1 = new JPanel();
  64.         panel1.setBackground(SystemColor.inactiveCaptionBorder);
  65.         panel1.setBounds(10, 11, 604, 100);
  66.         frame.getContentPane().add(panel1);
  67.         panel1.setLayout(null);
  68.  
  69.          
  70.  
  71.  
  72.         JLabel lblServerIP = new JLabel("Server IP");
  73.         lblServerIP.setBounds(10, 39, 60, 14);
  74.         panel1.add(lblServerIP);
  75.  
  76.         txtServerIP = new JTextField();
  77.         txtServerIP.setText("127.0.0.1");
  78.         txtServerIP.setBounds(73, 36, 160, 20);
  79.         panel1.add(txtServerIP);
  80.         txtServerIP.setColumns(10);
  81.  
  82.         JLabel lblServerPort = new JLabel("Server Port");
  83.         lblServerPort.setBounds(10, 64, 60, 14);
  84.         panel1.add(lblServerPort);
  85.  
  86.         txtServerPort = new JTextField();
  87.         txtServerPort.setText("14789");
  88.         txtServerPort.setBounds(73, 61, 160, 20);
  89.         panel1.add(txtServerPort);
  90.         txtServerPort.setColumns(10);
  91.  
  92.         JRadioButton rdbtnTcp = new JRadioButton("TCP");
  93.         rdbtnTcp.setSelected(true);
  94.         rdbtnTcp.setBackground(SystemColor.inactiveCaptionBorder);
  95.         buttonGroup.add(rdbtnTcp);
  96.         rdbtnTcp.setBounds(260, 30, 60, 23);
  97.         panel1.add(rdbtnTcp);
  98.  
  99.         JRadioButton rdbtnUdp = new JRadioButton("UDP");
  100.         rdbtnUdp.setBackground(SystemColor.inactiveCaptionBorder);
  101.         buttonGroup.add(rdbtnUdp);
  102.         rdbtnUdp.setBounds(260, 55, 53, 23);
  103.         panel1.add(rdbtnUdp);
  104.  
  105.         JLabel lblProtocol = new JLabel("Protocol");
  106.         lblProtocol.setBounds(260, 14, 46, 14);
  107.         panel1.add(lblProtocol);
  108.  
  109.         JButton btnConnect = new JButton("Connect to Server");
  110.         btnConnect.addActionListener(new ActionListener() {
  111.             public void actionPerformed(ActionEvent arg0) {
  112.             }
  113.         });
  114.         btnConnect.setBounds(326, 11, 109, 30);
  115.         panel1.add(btnConnect);
  116.  
  117.         JPanel panel2 = new JPanel();
  118.         panel2.setBackground(SystemColor.info);
  119.         panel2.setBounds(10, 122, 604, 418);
  120.         frame.getContentPane().add(panel2);
  121.         panel2.setLayout(null);
  122.  
  123.         enterField = new JTextField();
  124.         enterField.addActionListener(new ActionListener() {
  125.             public void actionPerformed(ActionEvent e) {
  126.                 sendData(e.getActionCommand());
  127.                 enterField.setText("");
  128.             }
  129.         });
  130.         enterField.setBounds(10, 372, 584, 35);
  131.         panel2.add(enterField);
  132.         enterField.setColumns(10);
  133.  
  134.         JTextArea displayArea = new JTextArea();
  135.         displayArea.setEditable(false);
  136.         displayArea.setBounds(10, 11, 584, 350);
  137.         panel2.add(displayArea);
  138.     }
  139.  
  140.     // public static String istemciNick = "CLIENT";
  141.  
  142.     private void connectToServer() throws IOException {
  143.         displayMessage("Connecting...");
  144.  
  145.         client = new Socket(txtServerIP.getText(),
  146.                 Integer.parseInt(txtServerPort.getText()));
  147.  
  148.         // display connection information
  149.         displayMessage("Connected to "
  150.                 + client.getInetAddress().getHostName());
  151.     }
  152.  
  153.     // get streams to send and receive data
  154.     private void getStreams() throws IOException {
  155.         // set up output stream for objects
  156.         output = new ObjectOutputStream(client.getOutputStream());
  157.         output.flush(); // flush output buffer to send header information
  158.  
  159.         // set up input stream for objects
  160.         input = new ObjectInputStream(client.getInputStream());
  161.  
  162.         displayMessage("Got I/O stream.");
  163.     }
  164.  
  165.     // process connection with server
  166.     private void processConnection() throws IOException {
  167.         // enable enterField so client user can send messages
  168.         setTextFieldEditable(true);
  169.  
  170.         do { // process messages sent from server
  171.  
  172.             // read message and display it
  173.             try {
  174.                 message = (String) input.readObject();
  175.                 displayMessage(message);
  176.             }
  177.  
  178.             // catch problems reading from server
  179.             catch (ClassNotFoundException classNotFoundException) {
  180.                 displayMessage("Unknown object type receieved.");
  181.             }
  182.  
  183.         } while (!message.contains("TERMINATE"));
  184.  
  185.     } // end method processConnection
  186.  
  187.     // close streams and socket
  188.     private void closeConnection() {
  189.         displayMessage("Closing connection...");
  190.         setTextFieldEditable(false); // disable enterField
  191.  
  192.         try {
  193.             output.close();
  194.             input.close();
  195.             client.close();
  196.             displayMessage("Connection closed...");
  197.  
  198.         } catch (IOException ioException) {
  199.             ioException.printStackTrace();
  200.         }
  201.     }
  202.  
  203.     // send message to server
  204.     private void sendData(String message) {
  205.         // send object to server
  206.         try {
  207.             output.writeObject("Client > " + message);
  208.             output.flush();
  209.             displayMessage("Client > " + message);
  210.         }
  211.         // process problems sending object
  212.         catch (IOException ioException) {
  213.             displayArea.append("Error writing object.");
  214.         }
  215.     }
  216.  
  217.     // utility method called from other threads to manipulate
  218.     // displayArea in the event-dispatch thread
  219.     private void displayMessage(final String messageToDisplay) {
  220.         // display message from GUI thread of execution
  221.         SwingUtilities.invokeLater(new Runnable() { //inner class to ensure GUI updates properly
  222.  
  223.                     public void run() // updates displayArea
  224.                     {
  225.                         displayArea.append("\n" + messageToDisplay);
  226.                         displayArea.setCaretPosition(displayArea.getText()
  227.                                 .length());
  228.                     }
  229.  
  230.                 } // end inner class
  231.  
  232.                 ); // end call to SwingUtilities.invokeLater
  233.     }
  234.  
  235.     // utility method called from other threads to manipulate
  236.     // enterField in the event-dispatch thread
  237.     private void setTextFieldEditable(final boolean editable) {
  238.         // display message from GUI thread of execution
  239.         SwingUtilities.invokeLater(new Runnable() { // inner class to ensure
  240.                     // GUI
  241.                     // // updates properly
  242.                     //
  243.                     public void run() // sets enterField's editability
  244.                     {
  245.                         enterField.setEditable(editable);
  246.                     }
  247.                     //
  248.                 } // end inner class
  249.                     //
  250.                 ); // end call to SwingUtilities.invokeLater
  251.     }
  252.  
  253.     // connect to server and process messages from server
  254.     private void runClient() {
  255.         // connect to server, get streams, process connection
  256.         try {
  257.             connectToServer(); // Step 1: Create a Socket to make connection
  258.             getStreams(); // Step 2: Get the input and output streams
  259.             processConnection(); // Step 3: Process connection
  260.         }
  261.         // server closed connection
  262.         catch (EOFException eofException) {
  263.             System.err.println("Server terminated connection.");
  264.         }
  265.         // process problems communicating with server
  266.         catch (IOException ioException) {
  267.             ioException.printStackTrace();
  268.         } finally {
  269.             closeConnection(); // Step 4: Close connection
  270.         }
  271.     } // end method runClient
  272.  
  273.     public static void main(String[] args) {
  274.         ClientGUI application;
  275.  
  276.         if (args.length == 0)
  277.             application = new ClientGUI("127.0.0.1");
  278.         else
  279.             application = new ClientGUI(args[0]);
  280.  
  281.         application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  282.         application.runClient();
  283.  
  284.     }
  285.  
  286. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement