P3udent 2019-09-02 22:27 采纳率: 0%
浏览 315

JAVA,GUI聊天功能,只做到发送信息和聊天记录,但是聊天记录不知道为什么不能不能查看

public class Demo_GUIChat extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private TextField tf;
private Button send;
private Button log;
private Button clear;
private Button shake;
private TextArea viewText;
private TextArea sendText;
private DatagramSocket socket;
private BufferedWriter bw;

public  Demo_GUIChat(){
    init();
    southPanel();
    centerPanel();
    event();
}

private void event() {
    this.addWindowFocusListener(new WindowAdapter() {
        @Override
        public void windowOpened(WindowEvent e) {
            try {
                socket.close();
                bw.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            System.exit(0);
        }
    });
       send.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            try {
                send();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    });
       log.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                logFile();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }

    });
}

private void logFile() throws IOException {
         bw.flush();       //刷新缓冲区
         FileInputStream fis = new FileInputStream("config.txt");
         ByteArrayOutputStream baos = new ByteArrayOutputStream(); //在内存中创建缓冲区

         int len;
         byte[] arr = new byte[8192];
         while((len = fis.read(arr)) != -1) {
             baos.write(arr,0,len);
         }

         String str = baos.toString();  //将内存中的内容转换成字符串
         viewText.setText(str);

         fis.close();
}

private void send() throws IOException {
    String message = sendText.getText(); //获取发送区域的内容
    String ip = tf.getText();            //获取IP地址
    DatagramPacket packet = 
            new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getByName(ip), 1213);
    socket.send(packet);                //发送数据

    String time = getCurrentTime();
    String str = time + "\r\n" + message + "\r\n\r\n";  //alt +shift +l 抽取局部变量
    viewText.append(str);           //将信息添加到显示区域中
    bw.write(str);                  //将信息写到数据库中
    sendText.setText("");

}



private String getCurrentTime() {
    Date d = new Date();       //创建当前日期对象
    SimpleDateFormat sdf  =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    return sdf.format(d);      //将时间格式化
}

private void centerPanel() {
    Panel center = new Panel();
    viewText = new TextArea();
    sendText = new TextArea(5,1);
    center.setLayout(new BorderLayout());  //设置为边界布局管理器
    center.add(sendText,BorderLayout.SOUTH);
    center.add(viewText,BorderLayout.CENTER);
    viewText.setEditable(false);
    viewText.setBackground(Color.WHITE);
    sendText.setFont(new Font("zzz",Font.PLAIN,15));
    viewText.setFont(new Font("zzz",Font.PLAIN,15));
    this.add(center,BorderLayout.CENTER);

}

private void southPanel() {
    Panel south = new Panel();
    tf = new TextField(15);
    tf.setText("127.0.0.1");
    send =  new Button("发送");
    log  =  new Button("记录");
    clear = new Button("清除");
    shake = new Button("震动");
    System.out.println(shake.getLabel());
    south.add(tf);
    south.add(send);
    south.add(log);
    south.add(clear);
    south.add(shake);
    this.add(south,BorderLayout.SOUTH);
}

public void init() {
    this.setLocation(500,50);
    this.setSize(400,600);
    new Reveive().start();
    try {
        socket = new DatagramSocket();
        bw = new BufferedWriter(new FileWriter("config.txt",true));  //需要在尾部追加 所以加上true
    } catch (Exception e) {
        e.printStackTrace();
    }
    this.setVisible(true);
    this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}

private class Reveive extends Thread{       //接收和发送需要同时执行,所以
    public void run() {
        try {
            DatagramSocket socket = new DatagramSocket(1213);
            DatagramPacket packet = new DatagramPacket(new byte[8192], 8192);
            while(true) {
            socket.receive(packet);         //接收信息
            byte[] arr = packet.getData();  //获取字节数据
            int len = packet.getLength();   //获取有效的字节数据
            String message = new String(arr,0,len); //转换成字符串
            String time = getCurrentTime();            //获取当前时间
            String ip = packet.getAddress().getHostAddress(); //获取ip地址
            String str = time + " " + ip + "对我说:\r\n" + message + "\r\n\r\n";
            viewText.append(str);
            bw.write(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
public static void main(String[] args) throws Exception {
    new Demo_GUIChat();
}

}

  • 写回答

1条回答

  • 毕小宝 博客专家认证 2019-09-03 09:27
    关注

    Button 对中文显示乱码,改成了英文标签了。不能查看的具体表现是什么呢?
    测试了一下,能发送,能回显上次运行时的数据,config.txt 内容也是可看的。
    图片说明

    评论

报告相同问题?

悬赏问题

  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 spring后端vue前端
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题