Hi guys,
I know i'm new here but i'm really in need of some help, I have been given a client side Java snippet of code that request the data and time from a Java server and have been tasked to combine it with a GUI interface. I have start the make the GUI but I have no idea how to incorporate the client request. I know there may be other ways of creating the GUI but it needs to be done like this, and the coding needs to be as simple as possible. I know you can't actually combine to two codes directly and have to add the request as an on-click action to a button but I have no idea how t do this as I am a complete novice.
Thanks in advance
Here's the GUI Coding
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DatagramGUI extends JFrame {
private JPanel jPMain;
private JLabel jLHost;
private JTextField jTFHost;
private JButton jBGet;
private JTextField jTFResult;
public static void main (String[] args)
{
DatagramGUI frame = new DatagramGUI();
frame.setSize(500, 300);
frame.DatagramGUI();
frame.setVisible(true);
frame.setTitle("Request date and time");
frame.setLocationRelativeTo(null);
}
private void DatagramGUI() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window = getContentPane();
window.setLayout(new BorderLayout());
jPMain = new JPanel();
jPMain.setLayout(new GridLayout (4,1));
window.add(jPMain);
jLHost = new JLabel("Enter Host IP");
jPMain.add(jLHost);
jTFHost = new JTextField("");
jPMain.add(jTFHost);
jBGet = new JButton("Request Date and Time");
jPMain.add(jBGet);
jTFResult = new JTextField("");
jPMain.add(jTFResult);
}
}
Here's the client/server Request Coding
import java.io.*;
import java.net.*;
import java.util.*;
/*
Compile: javac DatagramClient.java
Run: java DatagramClient // DatagramServer must be running
*/
public class DatagramClient
{
public static void main(String[] args) throws IOException
{
if (args.length != 1)
{
System.out.println("Usage: java DatagramClient <hostname>");
return;
}
// get a datagram socket
DatagramSocket socket = new DatagramSocket();
// send request
byte[] buf = new byte[256];
InetAddress address = InetAddress.getByName(args[0]);
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4455);
System.out.println ("About to request date & time");
socket.send(packet);
System.out.println ("Sent request for date and time");
// get response
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
System.out.println ("Received date & time");
// display response
String received = new String(packet.getData());
System.out.println("Remote Date and Time: " + received);
socket.close();
}
}