Source of TimeClient.java


  1: //TimeClient.java
  2: //Retrieves the time from a "time server" whose name is entered by the user.

  4: import java.awt.Color;
  5: import java.awt.FlowLayout;
  6: import java.awt.event.ActionEvent;
  7: import java.awt.event.ActionListener;
  8: import java.io.IOException;
  9: import java.net.Socket;
 10: import java.net.UnknownHostException;
 11: import java.util.Scanner;
 12: import javax.swing.JTextField;
 13: import javax.swing.JTextArea;
 14: import javax.swing.JButton;
 15: import javax.swing.JFrame;

 17: public class TimeClient extends JFrame
 18: implements ActionListener
 19: {
 20:     private JTextField hostInput;
 21:     private JTextArea display;
 22:     private JButton timeButton;
 23:     private JButton exitButton;

 25:     public static void main(String [] args)
 26:     {
 27:         TimeClient app = new TimeClient("Time Client");
 28:         app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 29:         app.setSize(550, 100);
 30:         app.setVisible(true);
 31:     }

 33:     TimeClient(String title)
 34:     {
 35:         super(title);
 36:         setLayout(new FlowLayout());
 37:         getContentPane().setBackground(Color.CYAN);
 38:         hostInput = new JTextField(48);
 39:         String prompt = "Enter host name above and click here " +
 40:                         "to see time at that host below ...";
 41:         timeButton = new JButton(prompt);
 42:         display = new JTextArea(1, 48);
 43:         exitButton = new JButton("Exit");
 44:         add(hostInput);
 45:         add(timeButton);
 46:         add(exitButton);
 47:         add(display);
 48:         timeButton.addActionListener(this);
 49:         exitButton.addActionListener(this);
 50:     }
 51: 
 52:     public void actionPerformed(ActionEvent event)
 53:     {
 54:         if (event.getSource() == exitButton) System.exit(0);
 55:         String hostName = hostInput.getText();
 56:         try
 57:         {
 58:             Socket socket = new Socket(hostName, 7013);
 59:             Scanner input = new Scanner(socket.getInputStream());
 60:             String theTime = input.nextLine();
 61:             display.setText("");
 62:             display.append("Time at " + hostName + " is " + theTime);
 63:             socket.close();
 64:         }
 65:         catch (UnknownHostException e)
 66:         {
 67:             display.setText("No such host!");
 68:         }
 69:         catch (IOException io)
 70:         {
 71:             display.setText(io.toString());
 72:         }
 73:     }
 74: }