黑马程序员技术交流社区
标题:
按教程写了个UDP实现的小聊天室,但是窗口显示有问题
[打印本页]
作者:
tomTemp
时间:
2016-2-7 13:30
标题:
按教程写了个UDP实现的小聊天室,但是窗口显示有问题
窗口只能显示一部分,要么是上面的对话框,要么显示底下的发送,抖屏等操作的操作框
C:\Users\Tom\Desktop\asdasd.png
本来是显示正常的,就是添加了一行获取本机ip的代码就不行了,以下是源码
package chatClub;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class QQFrame extends Frame {
private static final long serialVersionUID = 1L;
private static final int port = 6666;
private TextField tf_ip;
private Button send;
private Button record;
private Button clean;
private Button shake;
private TextArea ta_view;
private TextArea ta_send;
private DatagramSocket socket;
private BufferedWriter logFile;
public QQFrame() throws Exception {
init();
southPanel();
centerPanel();
event();
}
private void event() {
this.addWindowListener(new WindowAdapter() { // 窗口关闭
@Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
socket.close();
try {
logFile.close();
} catch (IOException e1) {
e1.printStackTrace();
}
System.exit(0);
}
});
send.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
send();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
record.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
viewRecord();
} catch (IOException e1) {
e1.printStackTrace();
} // 查看聊天记录
}
});
clean.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ta_view.setText("");
}
});
shake.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
send(new byte[] {-1},tf_ip.getText());
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
ta_send.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
// if (e.getKeyCode() == KeyEvent.VK_SPACE && e.isControlDown())
if (e.getKeyCode() == KeyEvent.VK_SPACE) {
try {
send();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
});
}
protected void shake() throws InterruptedException { // 震动
int x = this.getLocation().x;
int y = this.getLocation().y;
for (int i = 0; i < 4; i++) {
this.setLocation(x + 20, y);
Thread.sleep(20);
this.setLocation(x - 20, y + 20);
Thread.sleep(20);
this.setLocation(x, y - 20);
Thread.sleep(20);
this.setLocation(x, y);
}
}
protected void viewRecord() throws IOException {
logFile.flush(); // 先将缓冲区内容刷出
final Frame f_record = new Frame("聊天记录");
f_record.setLocation(400, 100);
f_record.setSize(600, 500);
f_record.setVisible(true);
TextArea ta_record = new TextArea();
f_record.add(ta_record);
ta_record.setEditable(false);
/*BufferedReader br = new BufferedReader(new FileReader("record"));
String msg;
while ((msg = br.readLine()) != null) {
ta_record.append(msg + "\n");
}
br.close();*/
FileInputStream fis = new FileInputStream("record");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] arr = new byte[8192];
int len;
while((len = fis.read(arr)) != -1) {
baos.write(arr, 0, len);
}
fis.close();
ta_record.setText(new String(baos.toByteArray(),0,baos.size()));
//or baos.toString()
f_record.addWindowListener(new WindowAdapter() {
//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
@Override
public void windowClosing(WindowEvent e) {
f_record.dispose(); // 为什么关闭的是另一个界面
// System.exit(0);
super.windowClosing(e);
}
});
}
protected void send() throws IOException {
String message = ta_send.getText();
String ip = tf_ip.getText();
ip = ip.trim() == "" ? "255.255.255.255" : ip;
if(message.equals("")) // 忽略空发送内容
return;
send(message.getBytes(), ip); // 调用重载方法
// alt + shift + l 抽取局部变量
String msgContent = " " + getCurrentTime() + " 我 对 " +
(ip.equals("255.255.255.255") ? "所有人" : ip) + "说:\n" + message + "\n";
ta_view.append(msgContent); // 聊天窗口中显示内容
logFile.write(msgContent); // 将信息写出到数据库
ta_send.setText(""); // 设置发送窗口为空
}
public void send(byte[] arr, String ip) throws UnknownHostException, // 重载的send
IOException {
DatagramPacket packet = new DatagramPacket(
arr,arr.length,InetAddress.getByName(ip),port);
socket.send(packet); // 发送数据
}
public String getCurrentTime() {
return new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss").format(new Date());
}
private void centerPanel() throws Exception {
Panel center = new Panel(new BorderLayout()); // 创建事件源
ta_view = new TextArea();
ta_send = new TextArea(5,1);
center.add(ta_view,BorderLayout.CENTER); // 添加
center.add(ta_send,BorderLayout.SOUTH);
ta_view.setEditable(false); // view不可写
ta_view.setBackground(Color.WHITE); // view设置颜色为白
// ta_view.setBackground(Color.darkGray); // view设置颜色为灰
// ta_send.setBackground(Color.darkGray); // send设置颜色为灰
ta_send.setFont(new Font("宋体",Font.PLAIN,18));
ta_view.setFont(new Font("宋体",Font.PLAIN,18));
this.add(center,BorderLayout.CENTER);
}
private void southPanel() throws IOException {
Panel south = new Panel();
tf_ip = new TextField(15);
send = new Button("发送");
record = new Button("记录");
clean = new Button("清屏");
shake = new Button("抖屏");
south.add(tf_ip);
south.add(send);
south.add(record);
south.add(clean);
south.add(shake);
send.setBackground(Color.BLUE);
// send.setSize(20, 20);
String ipAdress = InetAddress.getLocalHost().getHostAddress(); //获取本机ip地址
tf_ip.setText(ipAdress);
this.add(south,BorderLayout.SOUTH);
}
private void init() throws Exception {
setLayout(new BorderLayout());
setLocation(400, 100);
setSize(600, 600);
setTitle("咱俩聊天吧");
setIconImage(Toolkit.getDefaultToolkit().createImage("icon.jpg"));
logFile = new BufferedWriter( // 初始化聊天记录
new FileWriter("record",true));
new Receive().start(); // 开始接收消息
socket = new DatagramSocket();
setVisible(true);
}
private class Receive extends Thread { // 接收和发送需要同时执行,所以需要多线程的
public void run() {
try {
DatagramSocket socket = new DatagramSocket(port);
DatagramPacket packet = new DatagramPacket(new byte[8192], 8192);
int port;
int packetLen;
while (true) {
socket.receive(packet); // 接收信息
byte[] recv = packet.getData();
packetLen = packet.getLength();
if (packetLen == 1 && recv[0] == -1) {
shake();
continue;
}
String msg = new String(recv, 0, packet.getLength());
String ip = packet.getAddress().getHostAddress(); // 获取ip
port = packet.getPort();
String msgContent = " " + getCurrentTime()
+ " " + ip + "-" + port + " 对你说:\n" + msg + "\n\n";
ta_view.append(msgContent); // 显示收到的信息
logFile.write(msgContent); // 将收到的消息保存到数据库
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception {
new QQFrame();
}
}
复制代码
作者:
tomTemp
时间:
2016-2-7 13:31
就是253行那里添加了一行代码显示就不正常了
作者:
boboyuwu
时间:
2016-2-11 17:11
加我QQ 673862758 我刚写完我的聊天软件 或许可以帮助你
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2