?? chatroom.java
字號:
//客戶端程序
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Date;
import java.net.*;
import java.io.*;
public class ChatRoom extends JFrame
{
private JScrollPane sp;
private JTextArea ta;
private JTextField txt;
private JPanel p1,p2;
private JButton bt1,bt2;
private String words;//保存輸入框內容
private boolean t=false;//用來控制輸出
Socket socket=null;
BufferedReader br=null;
PrintWriter pw=null;
public ChatRoom(){
super("ChatRoom");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con=getContentPane();
p1=new JPanel();
bt1=new JButton("Send");
bt2=new JButton("Close");
p1.add(bt1);
p1.add(bt2);
p2=new JPanel();
ta=new JTextArea(10,40);
ta.setEditable(false);
sp=new JScrollPane(ta);
txt=new JTextField();
con.add(p1,BorderLayout.EAST);
con.add(sp,BorderLayout.WEST);
con.add(txt,BorderLayout.SOUTH);
this.pack();
setVisible(true);
ActionListener listener1=new ActionListener(){
public void actionPerformed(ActionEvent e)
{
JButton bt=(JButton)e.getSource();
try{
if(bt==bt2){
if(socket != null)socket.close();
System.exit(0);}
}catch(Exception ee){ee.printStackTrace();}
}
};
bt2.addActionListener(listener1);
try{
socket = new Socket("localhost", 3000);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
br = new BufferedReader(isr);
OutputStream os = socket.getOutputStream();
pw = new PrintWriter(os, true);
ActionListener listener2=new ActionListener(){
public void actionPerformed(ActionEvent e){
if(e.getSource()==bt1||e.getSource()==txt){
words=txt.getText();
pw.println(socket.getInetAddress()+": "+words);
txt.setText("");
}
}
};
bt1.addActionListener(listener2);
txt.addActionListener(listener2);
while(true){
String data = br.readLine();
ta.setText(ta.getText()+"\n"+data);
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{ if(pw !=null)pw.close();
if(br != null)br.close();
if(socket != null)socket.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
public static void main(String args[]){
new ChatRoom();
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -