-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatClientGUI.java
More file actions
93 lines (73 loc) · 2.7 KB
/
Copy pathChatClientGUI.java
File metadata and controls
93 lines (73 loc) · 2.7 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.net.*;
public class ChatClientGUI {
private JFrame frame;
private JTextArea chatArea;
private JTextField inputField;
private PrintWriter writer;
private String username;
public ChatClientGUI() {
askUsername();
buildGUI();
connectToServer();
}
private void askUsername() {
username = JOptionPane.showInputDialog("Enter your username:");
if (username == null || username.trim().isEmpty()) {
username = "User" + (int)(Math.random() * 1000);
}
}
private void buildGUI() {
frame = new JFrame("Chat - " + username);
frame.setSize(400, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
chatArea = new JTextArea();
chatArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(chatArea);
inputField = new JTextField();
JButton sendBtn = new JButton("Send");
sendBtn.addActionListener(e -> sendMessage());
inputField.addActionListener(e -> sendMessage());
frame.setLayout(new BorderLayout());
frame.add(scrollPane, BorderLayout.CENTER);
JPanel bottomPanel = new JPanel(new BorderLayout());
bottomPanel.add(inputField, BorderLayout.CENTER);
bottomPanel.add(sendBtn, BorderLayout.EAST);
frame.add(bottomPanel, BorderLayout.SOUTH);
frame.setVisible(true);
}
private void connectToServer() {
try {
Socket socket = new Socket("localhost", 5000);
writer = new PrintWriter(socket.getOutputStream(), true);
// Send username first
writer.println(username);
// Thread to read incoming messages
new Thread(() -> {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream())
);
String msg;
while ((msg = reader.readLine()) != null) {
chatArea.append(msg + "\n");
}
} catch (Exception ignored) {}
}).start();
} catch (Exception e) {
chatArea.append("❌ Unable to connect to server.\n");
}
}
private void sendMessage() {
String msg = inputField.getText().trim();
if (!msg.isEmpty()) {
writer.println(msg);
inputField.setText("");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(ChatClientGUI::new);
}
}