import java.awt.*;
為溆浦等地區(qū)用戶提供了全套網(wǎng)頁(yè)設(shè)計(jì)制作服務(wù),及溆浦網(wǎng)站建設(shè)行業(yè)解決方案。主營(yíng)業(yè)務(wù)為成都網(wǎng)站制作、成都網(wǎng)站設(shè)計(jì)、外貿(mào)營(yíng)銷網(wǎng)站建設(shè)、溆浦網(wǎng)站設(shè)計(jì),以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠(chéng)的服務(wù)。我們深信只要達(dá)到每一位用戶的要求,就會(huì)得到認(rèn)可,從而選擇與我們長(zhǎng)期合作。這樣,我們也可以走得更遠(yuǎn)!
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
public class ClientDemo01 {
public static void main(String[] args){
JFrame f=new JFrame("AA");
JPanel p1=new JPanel();
JPanel p2=new JPanel();
JTextArea ta=new JTextArea(15,30);
ta.setEditable(false); //文本域只讀
JScrollPane sp=new JScrollPane(ta); //滾動(dòng)窗格
JTextField tf=new JTextField(20);
JButton b=new JButton("發(fā)送");
p1.add(sp);
p2.add(tf);
p2.add(b);
f.add(p1,"Center");
f.add(p2,"South");
f.setBounds(300,300,360,300);
f.setVisible(true);
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Socket socket=null;
BufferedInputStream bis=null;
BufferedOutputStream bos=null;
try{
socket=new Socket("192.168.0.4",5000);
bis=new BufferedInputStream(socket.getInputStream());
bos=new BufferedOutputStream(socket.getOutputStream());
MyThread01 mt=new MyThread01(bis,ta);
mt.start();
}catch(Exception e){
e.printStackTrace();
}
b.addActionListener(new ButtonActionListener01(tf,ta,bos));
}
}
class ButtonActionListener01 implements ActionListener{
JTextField tf;
JTextArea ta;
BufferedOutputStream bos;
public ButtonActionListener01(JTextField tf,JTextArea ta,BufferedOutputStream bos){
this.tf=tf;
this.ta=ta;
this.bos=bos;
}
public void actionPerformed(ActionEvent e){
String message=tf.getText();
if(!message.equals("")){
tf.setText(""); //清空文本框
ta.append("AA:"+message+"\n"); //添加到文本域并換行
try{
bos.write(message.getBytes());
bos.flush();
}catch(Exception ex){
System.out.println("發(fā)送失敗");
}
}
}
}
class MyThread01 extends Thread{
BufferedInputStream bis;
JTextArea ta;
public MyThread01(BufferedInputStream bis,JTextArea ta){
this.bis=bis;
this.ta=ta;
}
public void run(){
try{
while(true){
byte[] b=new byte[100];
int length=bis.read(b);
String message=new String(b,0,length);
ta.append("BB:"+message+"\n");
}
}catch(Exception e){
e.printStackTrace();
}
}
} import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
public class ServerDemo01{
public static void main(String[] args){
JFrame f=new JFrame("BB");
JPanel p1=new JPanel();
JPanel p2=new JPanel();
JTextArea ta=new JTextArea(12,30); //文本域,第一個(gè)參數(shù)為行數(shù),第二個(gè)參數(shù)為列數(shù)
ta.setEditable(false); //文本域只讀
JScrollPane sp=new JScrollPane(ta); //滾動(dòng)窗格
JTextField tf=new JTextField(20);
JButton b=new JButton("發(fā)送");
p1.add(sp);
p2.add(tf);
p2.add(b);
f.add(p1,"Center");
f.add(p2,"South");
f.setBounds(300,300,360,300);
f.setVisible(true);
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ServerSocket server=null;
Socket socket=null;
BufferedInputStream bis=null;
BufferedOutputStream bos=null;
try{
server=new ServerSocket(5000);
//ta.append("等待AA連接...\n");
socket=server.accept();
//ta.append("AA已連接\n");
bis=new BufferedInputStream(socket.getInputStream());
bos=new BufferedOutputStream(socket.getOutputStream());
MyThread1 mt=new MyThread1(bis,ta);
mt.start();
}catch(Exception e){
e.printStackTrace();
}
b.addActionListener(new ButtonActionListener1(tf,ta,bos));
}
}
class ButtonActionListener1 implements ActionListener{
JTextField tf;
JTextArea ta;
BufferedOutputStream bos;
public ButtonActionListener1(JTextField tf,JTextArea ta,BufferedOutputStream bos){
this.tf=tf;
this.ta=ta;
this.bos=bos;
}
public void actionPerformed(ActionEvent e){
String message=tf.getText(); //獲取文本框中的內(nèi)容
if(!message.equals("")){
tf.setText(""); //清空文本框
ta.append("BB:"+message+"\n"); //添加到文本域并換行
try{
bos.write(message.getBytes());
bos.flush();
}catch(Exception ex){
System.out.println("發(fā)送失?。?);
}
}
}
}
class MyThread1 extends Thread{
BufferedInputStream bis;
JTextArea ta;
public MyThread1(BufferedInputStream bis,JTextArea ta){
this.bis=bis;
this.ta=ta;
}
public void run(){
try{
while(true){
byte[] b=new byte[100];
int length=bis.read(b);
String message=new String(b,0,length);
ta.append("AA:"+message+"\n");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
/**
* 基于UDP協(xié)議的聊天程序
*
* 2007.9.18
* */
//導(dǎo)入包
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.net.*;
public class Chat extends JFrame implements ActionListener
{
//廣播地址或者對(duì)方的地址
public static final String sendIP = "172.18.8.255";
//發(fā)送端口9527
public static final int sendPort = 9527;
JPanel p = new JPanel();
List lst = new List(); //消息顯示
JTextField txtIP = new JTextField(18); //填寫IP地址
JTextField txtMSG = new JTextField(20); //填寫發(fā)送消息
JLabel lblIP = new JLabel("IP地址:");
JLabel lblMSG = new JLabel("消息:");
JButton btnSend = new JButton("發(fā)送");
byte [] buf;
//定義DatagramSocket的對(duì)象必須進(jìn)行異常處理
//發(fā)送和接收數(shù)據(jù)報(bào)包的套接字
DatagramSocket ds = null;
//=============構(gòu)造函數(shù)=====================
public Chat()
{
CreateInterFace();
//注冊(cè)消息框監(jiān)聽器
txtMSG.addActionListener(this);
btnSend.addActionListener(this);
try
{
//端口:9527
ds =new DatagramSocket(sendPort);
}
catch(Exception ex)
{
ex.printStackTrace();
}
//============接受消息============
//匿名類
new Thread(new Runnable()
{
public void run()
{
byte buf[] = new byte[1024];
//表示接受數(shù)據(jù)報(bào)包
while(true)
{
try
{
DatagramPacket dp = new DatagramPacket(buf,1024,InetAddress.getByName(txtIP.getText()),sendPort);
ds.receive(dp);
lst.add("【消息來(lái)自】◆" + dp.getAddress().getHostAddress() + "◆"+"【說(shuō)】:" + new String (buf,0,dp.getLength()) /*+ dp.getPort()*/,0);
}
catch(Exception e)
{
if(ds.isClosed())
{
e.printStackTrace();
}
}
}
}
}).start();
//關(guān)閉窗體事件
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
System.out.println("test");
int n=JOptionPane.showConfirmDialog(null,"是否要退出?","退出",JOptionPane.YES_NO_OPTION);
if(n==JOptionPane.YES_OPTION)
{
dispose();
System.exit(0);
ds.close();//關(guān)閉ds對(duì)象//關(guān)閉數(shù)據(jù)報(bào)套接字
}
}
});
}
//界面設(shè)計(jì)布局
public void CreateInterFace()
{
this.add(lst,BorderLayout.CENTER);
this.add(p,BorderLayout.SOUTH);
p.add(lblIP);
p.add(txtIP);
p.add(lblMSG);
p.add(txtMSG);
p.add(btnSend);
txtIP.setText(sendIP);
//背景顏色
lst.setBackground(Color.yellow);
//JAVA默認(rèn)風(fēng)格
this.setUndecorated(true);
this.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
this.setSize(600,500);
this.setTitle("〓聊天室〓");
this.setResizable(false);//不能改變窗體大小
this.setLocationRelativeTo(null);//窗體居中
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.setVisible(true);
txtMSG.requestFocus();//消息框得到焦點(diǎn)
}
//===============================Main函數(shù)===============================
public static void main(String[]args)
{
new Chat();
}
//================================發(fā)送消息===============================
//消息框回車發(fā)送消息事件
public void actionPerformed(ActionEvent e)
{
//得到文本內(nèi)容
buf = txtMSG.getText().getBytes();
//判斷消息框是否為空
if (txtMSG.getText().length()==0)
{
JOptionPane.showMessageDialog(null,"發(fā)送消息不能為空","提示",JOptionPane.WARNING_MESSAGE);
}
else{
try
{
InetAddress address = InetAddress.getByName(sendIP);
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName(txtIP.getText()),sendPort);
ds.send(dp);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
txtMSG.setText("");//清空消息框
//點(diǎn)發(fā)送按鈕發(fā)送消息事件
if(e.getSource()==btnSend)
{
buf = txtMSG.getText().getBytes();
try
{
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName(txtIP.getText()),sendPort);
}
catch(Exception ex)
{
ex.printStackTrace();
}
txtMSG.setText("");//清空消息框
txtMSG.requestFocus();
}
}
}
共四個(gè)java文件,源代碼如下:
import java.awt.*;
import java.net.*;
import java.awt.event.*;
import java.io.*;
import java.util.Hashtable;
public class ChatArea extends Panel implements ActionListener,Runnable
{
Socket socket=null;
DataInputStream in=null;
DataOutputStream out=null;
Thread threadMessage=null;
TextArea 談話顯示區(qū),私聊顯示區(qū)=null;
TextField 送出信息=null;
Button 確定,刷新談話區(qū),刷新私聊區(qū);
Label 提示條=null;
String name=null;
Hashtable listTable;
List listComponent=null;
Choice privateChatList;
int width,height;
public ChatArea(String name,Hashtable listTable,int width,int height)
{
setLayout(null);
setBackground(Color.orange);
this.width=width;
this.height=height;
setSize(width,height);
this.listTable=listTable;
this.name=name;
threadMessage=new Thread(this);
談話顯示區(qū)=new TextArea(10,10);
私聊顯示區(qū)=new TextArea(10,10);
確定=new Button("送出信息到:");
刷新談話區(qū)=new Button("刷新談話區(qū)");
刷新私聊區(qū)=new Button("刷新私聊區(qū)");
提示條=new Label("雙擊聊天者可私聊",Label.CENTER);
送出信息=new TextField(28);
確定.addActionListener(this);
送出信息.addActionListener(this);
刷新談話區(qū).addActionListener(this);
刷新私聊區(qū).addActionListener(this);
listComponent=new List();
listComponent.addActionListener(this);
privateChatList=new Choice();
privateChatList.add("大家(*)");
privateChatList.select(0);
add(談話顯示區(qū));
談話顯示區(qū).setBounds(10,10,(width-120)/2,(height-120));
add(私聊顯示區(qū));
私聊顯示區(qū).setBounds(10+(width-120)/2,10,(width-120)/2,(height-120));
add(listComponent);
listComponent.setBounds(10+(width-120),10,100,(height-160));
add(提示條);
提示條.setBounds(10+(width-120),10+(height-160),110,40);
Panel pSouth=new Panel();
pSouth.add(送出信息);
pSouth.add(確定);
pSouth.add(privateChatList);
pSouth.add(刷新談話區(qū));
pSouth.add(刷新私聊區(qū));
add(pSouth);
pSouth.setBounds(10,20+(height-120),width-20,60);
}
public void setName(String s)
{
name=s;
}
public void setSocketConnection(Socket socket,DataInputStream in,DataOutputStream out)
{
this.socket=socket;
this.in=in;
this.out=out;
try
{
threadMessage.start();
}
catch(Exception e)
{
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==確定||e.getSource()==送出信息)
{
String message="";
String people=privateChatList.getSelectedItem();
people=people.substring(0,people.indexOf("("));
message=送出信息.getText();
if(message.length()0)
{
try {
if(people.equals("大家"))
{
out.writeUTF("公共聊天內(nèi)容:"+name+"說(shuō):"+message);
}
else
{
out.writeUTF("私人聊天內(nèi)容:"+name+"悄悄地說(shuō):"+message+"#"+people);
}
}
catch(IOException event)
{
}
}
}
else if(e.getSource()==listComponent)
{
privateChatList.insert(listComponent.getSelectedItem(),0);
privateChatList.repaint();
}
else if(e.getSource()==刷新談話區(qū))
{
談話顯示區(qū).setText(null);
}
else if(e.getSource()==刷新私聊區(qū))
{
私聊顯示區(qū).setText(null);
}
}
public void run()
{
while(true)
{
String s=null;
try
{
s=in.readUTF();
if(s.startsWith("聊天內(nèi)容:"))
{
String content=s.substring(s.indexOf(":")+1);
談話顯示區(qū).append("\n"+content);
}
if(s.startsWith("私人聊天內(nèi)容:"))
{
String content=s.substring(s.indexOf(":")+1);
私聊顯示區(qū).append("\n"+content);
}
else if(s.startsWith("聊天者:"))
{
String people=s.substring(s.indexOf(":")+1,s.indexOf("性別"));
String sex=s.substring(s.indexOf("性別")+2);
listTable.put(people,people+"("+sex+")");
listComponent.add((String)listTable.get(people));
listComponent.repaint();
}
else if(s.startsWith("用戶離線:"))
{
String awayPeopleName=s.substring(s.indexOf(":")+1);
listComponent.remove((String)listTable.get(awayPeopleName));
listComponent.repaint();
談話顯示區(qū).append("\n"+(String)listTable.get(awayPeopleName)+"離線");
listTable.remove(awayPeopleName);
}
Thread.sleep(5);
}
catch(IOException e)
{
listComponent.removeAll();
listComponent.repaint();
listTable.clear();
談話顯示區(qū).setText("和服務(wù)器的連接已中斷\n必須刷新瀏覽器才能再次聊天");
break;
}
catch(InterruptedException e)
{
}
}
}
}
ChatServer.java
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer
{
public static void main(String args[])
{
ServerSocket server=null;
Socket you=null;
Hashtable peopleList;
peopleList=new Hashtable();
while(true)
{
try
{
server=new ServerSocket(6666);
}
catch(IOException e1)
{
System.out.println("正在監(jiān)聽");
}
try {
you=server.accept();
InetAddress address=you.getInetAddress();
System.out.println("用戶的IP:"+address);
}
catch (IOException e)
{
}
if(you!=null)
{
Server_thread peopleThread=new Server_thread(you,peopleList);
peopleThread.start();
}
else {
continue;
}
}
}
}
class Server_thread extends Thread
{
String name=null,sex=null;
Socket socket=null;
File file=null;
DataOutputStream out=null;
DataInputStream in=null;
Hashtable peopleList=null;
Server_thread(Socket t,Hashtable list)
{
peopleList=list;
socket=t;
try {
in=new DataInputStream(socket.getInputStream());
out=new DataOutputStream(socket.getOutputStream());
}
catch (IOException e)
{
}
}
public void run()
{
while(true)
{ String s=null;
try
{
s=in.readUTF();
if(s.startsWith("姓名:"))
{
name=s.substring(s.indexOf(":")+1,s.indexOf("性別"));
sex=s.substring(s.lastIndexOf(":")+1);
boolean boo=peopleList.containsKey(name);
if(boo==false)
{
peopleList.put(name,this);
out.writeUTF("可以聊天:");
Enumeration enum=peopleList.elements();
while(enum.hasMoreElements())
{
Server_thread th=(Server_thread)enum.nextElement();
th.out.writeUTF("聊天者:"+name+"性別"+sex);
if(th!=this)
{
out.writeUTF("聊天者:"+th.name+"性別"+th.sex);
}
}
}
else
{
out.writeUTF("不可以聊天:");
}
}
else if(s.startsWith("公共聊天內(nèi)容:"))
{
String message=s.substring(s.indexOf(":")+1);
Enumeration enum=peopleList.elements();
while(enum.hasMoreElements())
{
((Server_thread)enum.nextElement()).out.writeUTF("聊天內(nèi)容:"+message);
}
}
else if(s.startsWith("用戶離開:"))
{
Enumeration enum=peopleList.elements();
while(enum.hasMoreElements())
{ try
{
Server_thread th=(Server_thread)enum.nextElement();
if(th!=thisth.isAlive())
{
th.out.writeUTF("用戶離線:"+name);
}
}
catch(IOException eee)
{
}
}
peopleList.remove(name);
socket.close();
System.out.println(name+"用戶離開了");
break;
}
else if(s.startsWith("私人聊天內(nèi)容:"))
{
String 悄悄話=s.substring(s.indexOf(":")+1,s.indexOf("#"));
String toPeople=s.substring(s.indexOf("#")+1);
Server_thread toThread=(Server_thread)peopleList.get(toPeople);
if(toThread!=null)
{
toThread.out.writeUTF("私人聊天內(nèi)容:"+悄悄話);
}
else
{
out.writeUTF("私人聊天內(nèi)容:"+toPeople+"已經(jīng)離線");
}
}
}
catch(IOException ee)
{
Enumeration enum=peopleList.elements();
while(enum.hasMoreElements())
{ try
{
Server_thread th=(Server_thread)enum.nextElement();
if(th!=thisth.isAlive())
{
th.out.writeUTF("用戶離線:"+name);
}
}
catch(IOException eee)
{
}
}
peopleList.remove(name);
try
{
socket.close();
}
catch(IOException eee)
{
}
System.out.println(name+"用戶離開了");
break;
}
}
}
}
import java.awt.*;
import java.io.*;
import java.net.*;
import java.applet.*;
import java.util.Hashtable;
ClientChat.java
public class ClientChat extends Applet implements Runnable
{
Socket socket=null;
DataInputStream in=null;
DataOutputStream out=null;
InputNameTextField 用戶提交昵稱界面=null;
ChatArea 用戶聊天界面=null;
Hashtable listTable;
Label 提示條;
Panel north, center;
Thread thread;
public void init()
{
int width=getSize().width;
int height=getSize().height;
listTable=new Hashtable();
setLayout(new BorderLayout());
用戶提交昵稱界面=new InputNameTextField(listTable);
int h=用戶提交昵稱界面.getSize().height;
用戶聊天界面=new ChatArea("",listTable,width,height-(h+5));
用戶聊天界面.setVisible(false);
提示條=new Label("正在連接到服務(wù)器,請(qǐng)稍等...",Label.CENTER);
提示條.setForeground(Color.red);
north=new Panel(new FlowLayout(FlowLayout.LEFT));
center=new Panel();
north.add(用戶提交昵稱界面);
north.add(提示條);
center.add(用戶聊天界面);
add(north,BorderLayout.NORTH);
add(center,BorderLayout.CENTER);
validate();
}
public void start()
{
if(socket!=nullin!=nullout!=null)
{ try
{
socket.close();
in.close();
out.close();
用戶聊天界面.setVisible(false);
}
catch(Exception ee)
{
}
}
try
{
socket = new Socket(this.getCodeBase().getHost(), 6666);
in=new DataInputStream(socket.getInputStream());
out=new DataOutputStream(socket.getOutputStream());
}
catch (IOException ee)
{
提示條.setText("連接失敗");
}
if(socket!=null)
{
InetAddress address=socket.getInetAddress();
提示條.setText("連接:"+address+"成功");
用戶提交昵稱界面.setSocketConnection(socket,in,out);
north.validate();
}
if(thread==null)
{
thread=new Thread(this);
thread.start();
}
}
public void stop()
{
try
{
socket.close();
thread=null;
}
catch(IOException e)
{
this.showStatus(e.toString());
}
}
public void run()
{
while(thread!=null)
{
if(用戶提交昵稱界面.get能否聊天()==true)
{
用戶聊天界面.setVisible(true);
用戶聊天界面.setName(用戶提交昵稱界面.getName());
用戶聊天界面.setSocketConnection(socket,in,out);
提示條.setText("祝聊天愉快!");
center.validate();
break;
}
try
{
Thread.sleep(100);
}
catch(Exception e)
{
}
}
}
}
InputNameTextField。java
import java.awt.*;
import java.net.*;
import java.awt.event.*;
import java.io.*;
import java.util.Hashtable;
public class InputNameTextField extends Panel implements ActionListener,Runnable
{
TextField nameFile=null;
String name=null;
Checkbox male=null,female=null;
CheckboxGroup group=null;
Button 進(jìn)入聊天室=null,退出聊天室=null;
Socket socket=null;
DataInputStream in=null;
DataOutputStream out=null;
Thread thread=null;
boolean 能否聊天=false;
Hashtable listTable;
public InputNameTextField(Hashtable listTable)
{
this.listTable=listTable;
nameFile=new TextField(10);
group=new CheckboxGroup();
male=new Checkbox("男",true,group);
female=new Checkbox("女",false,group);
進(jìn)入聊天室=new Button("進(jìn)入");
退出聊天室=new Button("退出");
進(jìn)入聊天室.addActionListener(this);
退出聊天室.addActionListener(this);
thread=new Thread(this);
add(new Label("昵稱:"));
add(nameFile);
add(male);
add(female);
add(進(jìn)入聊天室);
add(退出聊天室);
退出聊天室.setEnabled(false);
}
public void set能否聊天(boolean b)
{
能否聊天=b;
}
public boolean get能否聊天()
{
return 能否聊天;
}
public String getName()
{
return name;
}
public void setName(String s)
{
name=s;
}
public void setSocketConnection(Socket socket,DataInputStream in,DataOutputStream out)
{
this.socket=socket;
this.in=in;
this.out=out;
try{
thread.start();
}
catch(Exception e)
{
nameFile.setText(""+e);
}
}
public Socket getSocket()
{
return socket;
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==進(jìn)入聊天室)
{
退出聊天室.setEnabled(true);
if(能否聊天==true)
{
nameFile.setText("您正在聊天:"+name);
}
else
{
this.setName(nameFile.getText());
String sex=group.getSelectedCheckbox().getLabel();
if(socket!=nullname!=null)
{
try{
out.writeUTF("姓名:"+name+"性別:"+sex);
}
catch(IOException ee)
{
nameFile.setText("沒有連通服務(wù)器"+ee);
}
}
}
}
if(e.getSource()==退出聊天室)
{
try
{
out.writeUTF("用戶離開:");
}
catch(IOException ee)
{
}
}
}
public void run()
{
String message=null;
while(true)
{
if(in!=null)
{
try
{
message=in.readUTF();
}
catch(IOException e)
{
nameFile.setText("和服務(wù)器斷開"+e);
}
}
if(message.startsWith("可以聊天:"))
{
能否聊天=true;
break;
}
else if(message.startsWith("聊天者:"))
{
String people=message.substring(message.indexOf(":")+1);
listTable.put(people,people);
}
else if(message.startsWith("不可以聊天:"))
{
能否聊天=false;
nameFile.setText("該昵稱已被占用");
}
}
}
}
//以下引入包
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.applet.*;
public class regit extends JApplet implements ActionListener,ItemListener//接口
{
String s=null;
//對(duì)象的聲明
JLabel labelname,labelpass,labelsxe,labeladdress,labelmail,labelphone;//標(biāo)簽
JTextField textname,textaddress,textmail,textphone;//文本框
JRadioButton r1,r2;//單選按紐
ButtonGroup bg;//組
JPasswordField textpass;//密碼域
JButton buttonregit,buttonreset;//注冊(cè)按紐 重寫按紐
JPanel p;//面板
String sex;//定義性別字符串
URL url;//統(tǒng)一資源定位
BufferedWriter out1,out2;//流
BufferedReader in;
//布局方式
GridBagLayout gbl;
GridBagConstraints gc;
AppletContext co;//接口
//初始化
public void init()
{
//new 對(duì)象
labelname=new JLabel("用 戶 名:");
labelpass=new JLabel("用戶密碼:");
labelsxe=new JLabel("性別:");
labeladdress=new JLabel("地址:");
labelmail=new JLabel("電子郵件:");
labelphone=new JLabel("聯(lián)系電話:");
textname=new JTextField(15); textname.setForeground(Color.red);
textname.setToolTipText("請(qǐng)?jiān)谶@輸入你的用戶名");
textaddress=new JTextField(15);textaddress.setForeground(Color.red);
textaddress.setToolTipText("請(qǐng)?jiān)谶@輸入你的地址");
textmail=new JTextField(15); textmail.setForeground(Color.red);
textmail.setToolTipText("請(qǐng)?jiān)谶@里輸入你的E-mail地址");
textphone=new JTextField(15); textphone.setForeground(Color.red);
textphone.setToolTipText("請(qǐng)?jiān)谶@輸入你的電話號(hào)碼");
r1=new JRadioButton("男"); r1.setBackground(new Color(47,177,210));//設(shè)置顏色
r2=new JRadioButton("女"); r2.setBackground(new Color(47,177,210));//設(shè)置顏色
bg=new ButtonGroup();
bg.add(r1);bg.add(r2);//加入組,實(shí)現(xiàn)單選
textpass=new JPasswordField(15);
textpass.setToolTipText("在這里輸入密碼");
textpass.setForeground(Color.red);
buttonregit=new JButton("注冊(cè)"); buttonregit.setBackground(new Color(47,177,210));//設(shè)置顏色
buttonregit.setToolTipText("點(diǎn)擊按紐完成注冊(cè)");
buttonreset=new JButton("填寫"); buttonreset.setBackground(new Color(47,177,210));//設(shè)置顏色
buttonreset.setToolTipText("點(diǎn)擊按紐刷新重寫");
gbl=new GridBagLayout(); ///////////////////////////////////////
gc=new GridBagConstraints(); //////采用GridBagLayout布局方式////////
p=new JPanel();
p.setLayout(gbl);
p.setBackground(new Color(47,177,210));
this.getContentPane().add(p);//加入面板
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=2;
gc.gridy=2;
gbl.setConstraints(labelname,gc);
p.add(labelname);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=4;
gc.gridy=2;
gbl.setConstraints(textname,gc);
p.add(textname);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=2;
gc.gridy=4;
gbl.setConstraints(labelpass,gc);
p.add(labelpass);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=4;
gc.gridy=4;
gbl.setConstraints(textpass,gc);
p.add(textpass);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=2;
gc.gridy=6;
gbl.setConstraints(labelsxe,gc);
p.add(labelsxe);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=4;
gc.gridy=6;
gbl.setConstraints(r1,gc);
p.add(r1);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=5;
gc.gridy=6;
gbl.setConstraints(r2,gc);
p.add(r2);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=2;
gc.gridy=8;
gbl.setConstraints(labeladdress,gc);
p.add(labeladdress);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=4;
gc.gridy=8;
gbl.setConstraints(textaddress,gc);
p.add(textaddress);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=2;
gc.gridy=10;
gbl.setConstraints(labelmail,gc);
p.add(labelmail);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=4;
gc.gridy=10;
gbl.setConstraints(textmail,gc);
p.add(textmail);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=2;
gc.gridy=12;
gbl.setConstraints(labelphone,gc);
p.add(labelphone);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=4;
gc.gridy=12;
gbl.setConstraints(textphone,gc);
p.add(textphone);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=2;
gc.gridy=16;
gbl.setConstraints(buttonregit,gc);
p.add(buttonregit);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=4;
gc.gridy=16;
gbl.setConstraints(buttonreset,gc);
p.add(buttonreset);
/////////////////////////////////////////////
co=this.getAppletContext();
/////////////////////////////////////////////
buttonregit.addActionListener(this);//按紐事件的監(jiān)聽
buttonreset.addActionListener(this);//按紐事件的監(jiān)聽
r1.addItemListener(this);//選擇事件的監(jiān)聽
r2.addItemListener(this);//選擇事件的監(jiān)聽
textphone.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
//注冊(cè)按紐事件
if(e.getSource()==buttonregit)
{
String s1=textname.getText(); ////////////////////
String s2=new String(textpass.getPassword());////////////////////
String s3=textaddress.getText(); // 定義字符串 //
String s4=textmail.getText(); ////////////////////
String s5=textphone.getText(); ////////////////////
//判斷注冊(cè)資料 信息 是否為空
if(s1.length()==0 || s2.length()==0 ||s3.length()==0 ||s4.length()==0 ||s5.length()==0)
{
int error=JOptionPane.INFORMATION_MESSAGE;
JOptionPane.showMessageDialog(null,"資料不能為空,請(qǐng)重新注冊(cè)!","【溫馨提示】",error);
return;//彈出對(duì)話框并返回
}
try//寫入到txt文件
{
in=new BufferedReader(new FileReader("d:\\迷離視線聊天室\\password.txt"));
}
catch(Exception ee){}
String ss=s1;
try
{
while((s=in.readLine())!=null)
{
if(s.startsWith(ss))
{
JOptionPane.showMessageDialog(null,"用戶名已經(jīng)存在,請(qǐng)更換名字!");
textname.setText("");//設(shè)置為空,重新輸入
textpass.setText("");
textaddress.setText("");
textmail.setText("");
textphone.setText("");
return;
}
}
}
catch(Exception ee){}
///////////////////////////以上代碼判斷是否有同名
{
try
{
out1=new BufferedWriter(new FileWriter("d:\\迷離視線聊天室\\password.txt",true));
out2=new BufferedWriter(new FileWriter("d:\\迷離視線聊天室\\message.txt",true));
}//創(chuàng)建文件
catch(Exception ee)
{}
try
{
out1.write(s1+"#"+s2);//寫
out1.newLine();
out2.write("用戶名:"+s1);
out2.newLine();
out2.write("密碼:"+s2);
out2.newLine();
out2.write("性別:"+sex);
out2.newLine();
out2.write("地址:"+s3);
out2.newLine();
out2.write("電子郵件:"+s4);
out2.newLine();
out2.write("電話:"+s5);
out2.newLine();
out1.flush();
out2.flush();//清理緩沖
out1.close();
out2.close();
}
catch(Exception ee)
{}
JOptionPane.showMessageDialog(null,"注冊(cè)成功!");
try
{
String qss="";
url=new url(/qss);//連接上網(wǎng)址
co.showDocument(url);
}
catch(Exception exx)
{}
}
}
//////////////////////以下為回車事件
if(e.getSource()==textphone)
{
String s1=textname.getText(); ////////////////////
String s2=new String(textpass.getPassword());////////////////////
String s3=textaddress.getText(); // 定義字符串 //
String s4=textmail.getText(); ////////////////////
String s5=textphone.getText(); ////////////////////
//判斷注冊(cè)資料 信息 是否為空
if(s1.length()==0 || s2.length()==0 ||s3.length()==0 ||s4.length()==0 ||s5.length()==0)
{
int error=JOptionPane.INFORMATION_MESSAGE;
JOptionPane.showMessageDialog(null,"資料不能為空,請(qǐng)重新注冊(cè)!","【溫馨提示】",error);
return;//彈出對(duì)話框并返回
}
try//寫入到txt文件
{
in=new BufferedReader(new FileReader("d:\\迷離視線聊天室\\password.txt"));
}
catch(Exception ee){}
String ss=s1;
try
{
while((s=in.readLine())!=null)
{
if(s.startsWith(ss))
{
JOptionPane.showMessageDialog(null,"用戶名已經(jīng)存在,請(qǐng)更換名字!");
textname.setText("");//設(shè)置為空,重新輸入
textpass.setText("");
textaddress.setText("");
textmail.setText("");
textphone.setText("");
return;
}
}
}
catch(Exception ee){}
///////////////////////////以上代碼判斷是否有同名
{
try
{
out1=new BufferedWriter(new FileWriter("d:\\迷離視線聊天室\\password.txt",true));
out2=new BufferedWriter(new FileWriter("d:\\迷離視線聊天室\\message.txt",true));
}//創(chuàng)建文件
catch(Exception ee)
{}
try
{
out1.write(s1+"#"+s2);//寫
out1.newLine();
out2.write("用戶名:"+s1+"密碼:"+s2+"性別:"+sex+"地址:"+s3+"電子郵件:"+s4+"電話:"+s5);//寫
out2.newLine();
out1.flush();
out2.flush();//清理緩沖
out1.close();
out2.close();
}
catch(Exception ee)
{}
JOptionPane.showMessageDialog(null,"注冊(cè)成功!");
try
{
String qss="";
url=new url(/qss);//連接上網(wǎng)址
co.showDocument(url);
}
catch(Exception exx)
{}
}
}
if(e.getSource()==buttonreset)//刷新重寫事件
{
textname.setText("");
textpass.setText("");
textaddress.setText("");
textmail.setText("");
textphone.setText("");
}
}
//////////////////////////////////////////
//
public void itemStateChanged(ItemEvent ex)
{
if(ex.getSource()==r1)
{
sex=new String("男");
}
else if(ex.getSource()==r2)
{
sex=new String("女");
}
}
}
參考資料:試試看,剛在網(wǎng)上找的