📄 chatwindow.java
字号:
package com.lovo.event;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class ChatWindow extends JFrame implements Runnable{
public void run()//线程
{
try {
server = new ServerSocket(this.port);//服务器端口
while(true)
{
Socket s = server.accept();//等待
Scanner in = new Scanner(s.getInputStream());//输入转换
while(in.hasNextLine())//循环
{
history.append(in.nextLine()+"\n");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void init()//界面
{
this.setSize(500, 550);
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
this.setTitle("聊天中");
this.setLocationRelativeTo(null);
}
//基本按钮
JTextArea history;
JTextArea message;
int port;
ServerSocket server;
JTextField ip;
JTextField portText;
public ChatWindow(int a)//登陆事件
{
this.port = a;
init();
//容器设置
Container contentPane = this.getContentPane();
contentPane.setBackground(Color.cyan);
contentPane.setLayout(null);
//具体设置
history = new JTextArea();
history.setEditable(false);
JScrollPane jsp1 = new JScrollPane(history);
jsp1.setBounds(50, 20, 400, 300);
contentPane.add(jsp1);
JLabel jl1 = new JLabel("对方IP");
jl1.setBounds(50, 340, 80, 21);
contentPane.add(jl1);
ip = new JTextField();
ip.setBounds(130, 340, 120, 21);
contentPane.add(ip);
JLabel jl2 = new JLabel("端口号");
jl2.setBounds(300, 340, 80, 21);
contentPane.add(jl2);
portText = new JTextField();
portText.setBounds(380, 340, 50, 21);
contentPane.add(portText);
message = new JTextArea();
JScrollPane jsp2 = new JScrollPane(message);
jsp2.setBounds(50, 380, 400, 100);
contentPane.add(jsp2);
JButton button = new JButton("发送");
//事件监听
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try {
Socket s = new Socket(ip.getText(),Integer.parseInt(portText.getText()));
PrintWriter out = new PrintWriter(s.getOutputStream(),true);
out.println(message.getText());
history.append(message.getText()+"\n");
out.close();
s.close();
message.setText("");
} catch (NumberFormatException e1) {
e1.printStackTrace();
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
//事件
button.setBounds(200, 480, 80, 25);
contentPane.add(button);
this.setVisible(true);
Thread th = new Thread(this);
th.start();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -