[Head First Java] - Swing做一个简单的客户端

参考 - P487

1. vscode配置java的格式

在这里插入图片描述
点击左下角齿轮 -> 设置 -> 打开任意的setting.json输入如下代码

{
    
    
	 code-runner.executorMap": {
    
    
        "java": "cd $dir && javac -encoding utf-8 $fileName && java $fileNameWithoutExt"
    },
}

之后再执行就可以了
在这里插入图片描述

2. 建议的聊天客户端如下

import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class SimpleChatClientA {
    
    
    JTextField outgoing;
    PrintWriter writer;
    Socket sock;

    public void go() {
    
    
        JFrame frame = new JFrame("Ludicrously Simple Chat Client");
        JPanel mainPanel = new JPanel();
        outgoing = new JTextField(20);
        JButton sendButton = new JButton("Send");
        sendButton.addActionListener(new SendButtonListener());
        mainPanel.add(outgoing);
        mainPanel.add(sendButton);
        frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
        setUpNetworking();
        frame.setSize(400, 500);
        frame.setVisible(true);
    }

    private void setUpNetworking(){
    
    
        try {
    
    
            sock = new Socket("127.0.0.1", 5000);
            writer = new PrintWriter(sock.getOutputStream());
            System.out.println("networking established");
        } catch (IOException ex) {
    
    
            ex.printStackTrace();
        }
    }

    public class SendButtonListener implements ActionListener {
    
    
        public void actionPerformed(ActionEvent ev) {
    
    
            try {
    
    
                writer.println(outgoing.getText());
                writer.flush();
            } catch (Exception ex) {
    
    
                ex.printStackTrace();
            }
            outgoing.setText("");
            outgoing.requestFocus();
        }
    }   // 关闭SendButton Listener内部类

    public static void main(String[] args) {
    
    
        new SimpleChatClientA().go();
    }
}   // 关闭外部类

猜你喜欢

转载自blog.csdn.net/piano9425/article/details/109634205