⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 chat.java

📁 实现简单的通信功能,让自己掌握socket编程
💻 JAVA
字号:
package com.tarena.chat1;import java.awt.event.*;import javax.swing.*;import java.awt.*;public class Chat extends JDialog {	private JButton startBtn;	private JButton stopBtn;	private Container contentPane;	private JTextField userName;	private JTextField host;	private String title;		public Chat(String title) {		this.title=title;		setTitle(title);		setSize(250, 150);		contentPane = getContentPane();		GridBagLayout gbl = new GridBagLayout();		contentPane.setLayout(gbl);		GridBagConstraints gbc = new GridBagConstraints();		JLabel userLbl = new JLabel("User Name:");		JLabel hostLbl = new JLabel("Chat Host:");		userName = new JTextField();		host = new JTextField();		userName.setText("Guest");		host.setText("239.255.255.255");		gbc.fill = GridBagConstraints.BOTH;		gbc.gridwidth = 2;		makeComponent(gbl, userLbl, gbc);		gbc.gridwidth = GridBagConstraints.REMAINDER;		makeComponent(gbl, userName, gbc);		gbc.gridwidth = 2;		makeComponent(gbl, hostLbl, gbc);		gbc.gridwidth = GridBagConstraints.REMAINDER;		makeComponent(gbl, host, gbc);		startBtn = new JButton("start");		ActionListener ca=new ActionListener(){			public void actionPerformed(ActionEvent ae) {				connect();			}		};		startBtn.addActionListener(ca);		userName.addActionListener(ca);		host.addActionListener(ca);		stopBtn = new JButton("stop");		stopBtn.addActionListener(new ActionListener() {			public void actionPerformed(ActionEvent ae) {				System.exit(0);			}		});		gbc.fill = GridBagConstraints.CENTER;		gbc.gridwidth = 2;		makeComponent(gbl, startBtn, gbc);		gbc.gridwidth = GridBagConstraints.REMAINDER;		makeComponent(gbl, stopBtn, gbc);		setDefaultCloseOperation(DISPOSE_ON_CLOSE);		Dimension screenSize = 			Toolkit.getDefaultToolkit().getScreenSize();		setLocation((int)(screenSize.getWidth()-this.getWidth())/2,				(int)(screenSize.getHeight()-this.getHeight())/2);	}	private void makeComponent(GridBagLayout gbl, Component c,			GridBagConstraints gbc) {		gbl.setConstraints(c, gbc);		contentPane.add(c);	}	private void connect() {		String user=userName.getText();		if(user.indexOf(Helper.TAG)>=0){			userName.setText("");			return;		}		IConnecter conn =new UDPConnecter(				host.getText(), 9998, userName.getText());		if (conn.connect()) {			setVisible(false);			ISender sender = conn.getSender();			View v = new View(sender);			ReceiverThread rt = 				new ReceiverThread(v, conn.getReceiver());			v.showMe(title);			rt.start();		} else {			System.out.println("Can not connected!");			setVisible(true);		}	}	public static void main(String[] args) {		(new Chat("My Chat Room")).setVisible(true);	}}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -