📄 chatdemo.java
字号:
package english;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class ChatDemo extends JFrame {
JPanel mainPanel;
JPanel panel1, panel2, panel3;
JLabel yourName, myName;
JTextField text1;
JButton btnSend;
JTextArea textArea1;
JScrollPane scrollPanel;
JButton btnConnect, btnSave, btnClose;
ServerThread srvThread;
ClientThread cltThread;
String myNickname, yourNickname;
boolean chgFlag;
public boolean hasClient;
public boolean hasServer;
public static void main(String[] args) {
final ChatDemo frame = new ChatDemo();
frame.setTitle("Chat Demo");
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
}
catch (Exception e) {
e.printStackTrace();
}
frame.myNickname = JOptionPane.showInputDialog(frame, "请输入你的昵称:", "");
if ((frame.myNickname == null) || (frame.myNickname.equals("")))
System.exit(0);
frame.chgFlag = false;
frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
frame.confirmClose();
}
});
frame.addComponent();
frame.pack();
frame.setVisible(true);
frame.hasServer = false;
frame.hasClient = false;
frame.srvThread = new ServerThread("ServerThread", frame);
frame.srvThread.start();
}
public void addComponent() {
mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
getContentPane().add(mainPanel);
panel1 = new JPanel();
panel2 = new JPanel();
panel3 = new JPanel();
yourName = new JLabel("对方昵称:");
myName = new JLabel("我的昵称:" + myNickname);
panel1.setLayout(new GridLayout(0,2));
panel1.add(yourName);
panel1.add(myName);
text1 = new JTextField(40);
text1.addActionListener(new ChatActionListenerClass(this));
text1.setActionCommand("输入文字");
btnSend = new JButton("发送");
btnSend.addActionListener(new ChatActionListenerClass(this));
btnSend.setActionCommand("发送");
panel2.add(text1);
panel2.add(btnSend);
textArea1 = new JTextArea(8, 50);
textArea1.setEditable(false);
textArea1.setLineWrap(true);
textArea1.setWrapStyleWord(true);
scrollPanel = new JScrollPane(textArea1, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
btnConnect = new JButton("连接");
btnSave = new JButton("保存");
btnClose = new JButton("关闭");
btnConnect.addActionListener(new ChatActionListenerClass(this));
btnSave.addActionListener(new ChatActionListenerClass(this));
btnClose.addActionListener(new ChatActionListenerClass(this));
btnConnect.setActionCommand("连接");
btnSave.setActionCommand("保存");
btnClose.setActionCommand("关闭");
panel3 = new JPanel();
panel3.setLayout(new FlowLayout(FlowLayout.CENTER, 15, 5));
panel3.add(btnConnect);
panel3.add(btnSave);
panel3.add(btnClose);
mainPanel.add(panel1);
mainPanel.add(panel2);
mainPanel.add(scrollPanel);
mainPanel.add(panel3);
}
void confirmClose() {
if (chgFlag) {
int returnValue = JOptionPane.showConfirmDialog(null, "聊天记录还未保存,是否保存?", "保存记录", JOptionPane.YES_NO_CANCEL_OPTION);
if (returnValue == JOptionPane.YES_OPTION) {
boolean saveFlag = saveFile();
if (saveFlag)
System.exit(0);
}
else if (returnValue == JOptionPane.NO_OPTION) {
System.exit(0);
}
}
else {
System.exit(0);
}
}
boolean saveFile() {
JFileChooser fc = new JFileChooser();
fc.setDialogType(JFileChooser.SAVE_DIALOG);
int rtnValue = fc.showOpenDialog(this);
if (rtnValue == JFileChooser.APPROVE_OPTION) {
try {
File file1 = fc.getSelectedFile();
FileWriter writer1 = new FileWriter(file1);
writer1.write(textArea1.getText());
writer1.close();
return true;
} catch (IOException e) {
return false;
}
}
else {
return false;
}
}
public void chatActionPerformed(ActionEvent e) {
if ("输入文字".equals(e.getActionCommand()) || "发送".equals(e.getActionCommand())) {
String strText = text1.getText();
addText(myNickname, strText);
sendMessage(strText);
}
else if ("连接".equals(e.getActionCommand())) {
cltThread = new ClientThread("ClientThread", this);
cltThread.start();
}
else if ("保存".equals(e.getActionCommand())) {
boolean saveFlag = saveFile();
if (saveFlag)
chgFlag = false;
}
else if ("关闭".equals(e.getActionCommand())) {
confirmClose();
}
}
void addText(String nickname, String strText) {
textArea1.append(nickname + ": " + strText + "\r\n");
chgFlag = true;
text1.selectAll();
textArea1.setCaretPosition(textArea1.getDocument().getLength());
}
public void sendMessage(String msg) {
Socket sender;
if (hasClient)
sender = cltThread.cltSocket;
else
sender = srvThread.connSocket;
if (sender == null)
return;
try {
PrintWriter out = new PrintWriter(sender.getOutputStream(), true);
out.println(msg);
} catch (IOException e) {}
}
}
class ChatActionListenerClass implements ActionListener {
ChatDemo frame;
public ChatActionListenerClass(ChatDemo frame) {
this.frame = frame;
}
public void actionPerformed(ActionEvent e) {
frame.chatActionPerformed(e);
}
}
class ServerThread extends Thread {
ServerSocket srvSocket;
Socket connSocket;
ChatDemo frame;
public ServerThread(String str, ChatDemo frame) {
super(str);
this.frame = frame;
}
public void run() {
try {
srvSocket = new ServerSocket(4444);
srvSocket.setSoTimeout(1000);
while (!frame.hasClient && !frame.hasServer) {
try {
connSocket = srvSocket.accept();
frame.hasServer = true;
} catch (SocketTimeoutException t) {}
}
if (frame.hasClient) {
srvSocket.close();
if (connSocket != null)
connSocket.close();
}
else {
BufferedReader in = new BufferedReader(new InputStreamReader(connSocket.getInputStream()));
String inStr;
frame.yourNickname = in.readLine();
frame.yourName.setText("对方昵称:" + frame.yourNickname);
frame.sendMessage(frame.myNickname);
while ((inStr = in.readLine()) != null) {
frame.addText(frame.yourNickname, inStr);
}
in.close();
connSocket.close();
srvSocket.close();
}
} catch (IOException e) {
System.exit(0);
}
}
}
class ClientThread extends Thread {
ChatDemo frame;
Socket cltSocket;
public ClientThread(String str, ChatDemo frame) {
super(str);
this.frame = frame;
}
public void run() {
String hostName;
hostName = JOptionPane.showInputDialog(frame, "请输入对方电脑的名称或IP地址:", "");
if ((hostName == null) || (hostName.equals("")))
return;
try {
cltSocket = new Socket(hostName, 4444);
} catch (IOException e) {
JOptionPane.showMessageDialog(frame, "无法连接到对方电脑。");
return;
}
frame.hasClient = true;
frame.sendMessage(frame.myNickname);
try {
BufferedReader in = new BufferedReader(new InputStreamReader(cltSocket.getInputStream()));
String inStr;
inStr = in.readLine();
frame.yourNickname = inStr;
frame.yourName.setText("对方昵称:" + inStr);
while ((inStr = in.readLine()) != null) {
frame.addText(frame.yourNickname, inStr);
}
in.close();
cltSocket.close();
} catch (IOException e) {}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -