SimpleChatClient after changes for a7hu
SimpleChatClient after changes for a7huunknown
java
4 years ago
3.4 kB
6
Indexable
package chatClient;
import java.awt.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
import java.awt.event.*;
public class SimpleChatClient {
JTextArea incoming;
JTextField outgoing;
Socket sock;
PrintWriter writer;
JButton button;
BufferedReader readMe = setUpNetworking();
public static void main(String[] args) {
SimpleChatClient instance = new SimpleChatClient();
instance.go();
}// ends the static main method
public void go() {
JFrame frame = new JFrame("SimpleChatClient");
JPanel panel = new JPanel();
incoming = new JTextArea(15,20);
incoming.setLineWrap(true);
incoming.setWrapStyleWord(true);
incoming.setEditable(false);
// now lets add a scroller to the incoming section
JScrollPane incomingScroller = new JScrollPane(incoming);
incomingScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
incomingScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
outgoing = new JTextField(20); // this is where you type your messge
button = new JButton("Send!!!");
button.addActionListener(new sendButtonListener());
panel.add(incomingScroller);
panel.add(outgoing);
panel.add(button);// we will define this function later on
Thread readerThread = new Thread (new IncomingReader()); //creates a thread to read the incoming messages continously
readerThread.start();
// now lets add everythign to the frame
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.setSize(500,400);
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}// ends the public void go, gui building finished
// setup networking
public BufferedReader setUpNetworking() {
try {
sock = new Socket ("127.0.0.1", 4889);
writer = new PrintWriter(sock.getOutputStream());
InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
System.out.println("Networking Establishe successfully");
return reader;
} catch (IOException ex) {
ex.printStackTrace();
return new BufferedReader(null);
}
} // ends the setUpNetworking
public class sendButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
try {
writer.println(outgoing.getText());
writer.flush();
} catch (Exception ex) {
ex.printStackTrace();
}
outgoing.setText("");
outgoing.requestFocus();
}
} // ends the sendButtonListener
public class IncomingReader implements Runnable{
public void run() {
String message ;
try {
while ((message = SimpleChatClient.this.readMe.readLine())!= null) {
System.out.println("read " + message);
incoming.append(message + "\n");
} // ends the while loop
} catch (IOException ex) {
ex.printStackTrace();
}
}
} // ends the incoming reader class
} // ends the public class SimpleChatClientEditor is loading...