-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatClient
More file actions
76 lines (62 loc) · 2.78 KB
/
ChatClient
File metadata and controls
76 lines (62 loc) · 2.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class ChatClient {
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame("Chat Client");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 400);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.setBackground(new Color(53, 56, 64));
JTextArea chatArea = new JTextArea();
chatArea.setEditable(false);
chatArea.setFont(new Font("Arial", Font.PLAIN, 14));
chatArea.setForeground(Color.WHITE);
chatArea.setBackground(new Color(53, 56, 64));
JScrollPane scrollPane = new JScrollPane(chatArea);
scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JPanel bottomPanel = new JPanel(new BorderLayout());
bottomPanel.setBackground(new Color(53, 56, 64));
ImageIcon avatarIcon = new ImageIcon("path/to/your/avatar.png");
JLabel avatarLabel = new JLabel(avatarIcon);
avatarLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JTextField messageField = new JTextField(30);
messageField.setFont(new Font("Arial", Font.PLAIN, 14));
JButton sendButton = new JButton("Send");
sendButton.setForeground(Color.WHITE);
sendButton.setBackground(new Color(66, 134, 244));
bottomPanel.add(avatarLabel, BorderLayout.WEST);
bottomPanel.add(messageField, BorderLayout.CENTER);
bottomPanel.add(sendButton, BorderLayout.EAST);
mainPanel.add(scrollPane, BorderLayout.CENTER);
mainPanel.add(bottomPanel, BorderLayout.SOUTH);
frame.setContentPane(mainPanel);
frame.setVisible(true);
String serverAddress = "localhost";
int port = 12345;
Socket socket = new Socket(serverAddress, port);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
sendButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String message = messageField.getText();
out.println(message);
chatArea.append("Client: " + message + "\n");
messageField.setText("");
}
});
while (true) {
String receivedMessage = in.readLine();
if (receivedMessage != null) {
chatArea.append("Server: " + receivedMessage + "\n");
}
}
}
}