java五子棋代码解析 java五子棋的简单思路( 五 )


JButton connectButton = new JButton();
JButton disConnectButton = new JButton();
// 聊天室内容的文本域
JTextArea chatContentTextArea = new JTextArea(9, 30);
// 发送消息的按钮
JButton sendMsgButton = new JButton();
// 消息输入框
JTextField msgTextField = new JTextField(20);
JLabel msglabel = new JLabel();
// 聊天室用户列表
java.awt.List peopleList = new java.awt.List(10);
/*以下定义数据流和网络变量*/
Socket soc = null;
PrintStream ps = null;
// 客户端侦听服务器消息的线程
ClentListener listener = null;
public ChatClient() {
init();
}
// 初始化图形界面
public void init() {
this.setTitle("聊天室客户端");
// 初始化按钮和标签
nameLabel.setText("姓名:");
connectButton.setText("连 接");
connectButton.addActionListener(this);
disConnectButton.setText("断 开");
disConnectButton.addActionListener(this);
// 设置聊天内容不可编辑
chatContentTextArea.setEditable(false);
sendMsgButton.setText("发 送");
sendMsgButton.addActionListener(this);
msgTextField.setText("请输入聊天信息");
//panel1放置输入姓名和连接两个按钮
JPanel panel1 = new JPanel();
panel1.setLayout(new FlowLayout());
panel1.add(nameLabel);
panel1.add(nameTextField);
panel1.add(connectButton);
panel1.add(disConnectButton);
//用于放置聊天信息显示和聊天人员列表
JPanel panel2 = new JPanel();
panel2.setLayout(new FlowLayout());
JScrollPane pane1 = new JScrollPane(chatContentTextArea);
pane1.setBorder(new TitledBorder(BorderFactory.createEtchedBorder(
Color.white, new Color(134, 134, 134)), "聊天内容"));
panel2.add(pane1);
JScrollPane pane2 = new JScrollPane(peopleList);
pane2.setBorder(new TitledBorder(BorderFactory.createEtchedBorder(
Color.white, new Color(134, 134, 134)), "用户列表"));
panel2.add(pane2);
//用于放置发送信息区域
JPanel panel3 = new JPanel();
panel3.setLayout(new FlowLayout());
panel3.add(msglabel);
panel3.add(msgTextField);
panel3.add(sendMsgButton);
// 将组件添加到界面
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(panel1, BorderLayout.NORTH);
this.getContentPane().add(panel2, BorderLayout.CENTER);
this.getContentPane().add(panel3, BorderLayout.SOUTH);
this.pack();
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI(this);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 关闭聊天室客户端事件
*/
protected void processWindowEvent(WindowEvent e){
super.processWindowEvent(e);
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
// 如果是关闭聊天室客户端,则断开连接
disconnect();
dispose();
System.exit(0);
}
}
/**
* 处理按钮事件
*/
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == connectButton){
// 如果点击连接按钮
if (soc == null) {
try {
// 使用端口2525实例化一个本地套接字
soc = new Socket(InetAddress.getLocalHost(), Constants.SERVER_PORT);
// 在控制台打印实例化的结果
System.out.println(soc);
//将ps指向soc的输出流
ps = new PrintStream(soc.getOutputStream());
//定义一个字符缓冲存储发送信息
StringBuffer info = new StringBuffer(Constants.CONNECT_IDENTIFER).append(Constants.SEPERATOR);
//其中INFO为关键字让服务器识别为连接信息
//并将name和ip用":"分开 , 在服务器端将用一个

推荐阅读