I have one project named P2PTicTac. I have one file named layout.java. and one with CLient.java. I have made simple GridView in layout file with 9 buttons in 3*3 Grid.
I have run two threads in client.java. One for reading the data from server and one for writing data to server. I have actionListeners in Layout file. When I click on any button in layout ,
then I want to send one number to server using the thread which I run in client.java. And then server will send me a number which I will use to update my GUI in layout.java.
I have made both the files completely but I don't know how to give data to the thread so that I could send to server and how to update GUI when I get response from server in write thread. I hope I am clear. I know thread is a separate entity. But How can I do my task? I don't want code. I want logic how to do this thing?
P.S I have used AWT for making the GUI and I used simple THREAD API of Java to run two threads in the CLient.java class.
CLient.Java
sReadThread = new Thread(new Runnable() {
@Override
public void run() {
Scanner scanner = new Scanner(System.in);
System.out.println(describeUserCommands());
while (true) {
// System.out.println("User: ");
String userInput = scanner.nextLine();
if (userInput.equalsIgnoreCase("help"))
System.out.println(describeUserCommands());
else if (userInput.startsWith("bye")) {
break;
} else {
cOut.println(userInput);
//System.out.println("Command sent: " + userInput);
}
}
try {
scanner.close();
System.out.println("User closed connection!!");
cOut.close();
sWriteThread.interrupt();
cIn.close();
mSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
sWriteThread = new Thread(new Runnable() {
@Override
public void run() {
String fromServer = null;
try {
while ((fromServer = cIn.readLine()) != null) {
System.out.println(fromServer);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
sReadThread.start();
sWriteThread.start();
Layout.java
public First() {
mainFrame = new Frame();
mainFrame.setLayout(new GridLayout(0, 3));
mainFrame.setSize(400, 400);
Button button = new Button();
button.setActionCommand("button 1");
button.addActionListener(new ButtonClassListener());
mainFrame.add(button);
mainFrame.add(new Button());
mainFrame.add(new Button());
mainFrame.add(new Button());
mainFrame.add(new Button());
mainFrame.add(new Button());
mainFrame.add(new Button());
mainFrame.add(new Button());
mainFrame.add(new Button());
Button button2 = new Button("Exit");
button.setActionCommand("Exit");
button2.addActionListener(new ButtonClassListener());
mainFrame.add(button2);
mainFrame.setVisible(true);
}
public class ButtonClassListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if(command.equals("button 1")) {
Button b = (Button)e.getSource();
b.setLabel("Cross");
b.setName("Cross");
b.setEnabled(false);
}
else if(command.equals("Exit")) {
System.exit(0);
}
}
}
}
Thanks in advance.