?? clientframe.java
字號:
package chatclient2;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
public class clientFrame extends JFrame implements ActionListener,Runnable{
JTextField input=new JTextField(20);
JTextArea area=new JTextArea(20,20);
JTextField connection=new JTextField(20);
JButton btn=new JButton("connect");
JPanel panel=new JPanel();
Socket socket=null;
DataInputStream reader=null;
PrintStream writer=null;
public boolean connected=false;
public clientFrame() {
JPanel contentPane=(JPanel)this.getContentPane();
contentPane.add(panel,BorderLayout.NORTH);
panel.add(connection);
panel.add(btn);
btn.addActionListener(this);
input.addActionListener(this);
contentPane.add(area,BorderLayout.CENTER);
contentPane.add(input,BorderLayout.SOUTH);
this.pack();
/////////////
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
try {
if(socket!=null)
socket.close();
writer.close();
System.exit(0);
}catch(Exception e){
JOptionPane.showMessageDialog(null,"abnormally stopping");
}
}
});
////////////
}
public static void main(String[] args) {
clientFrame client = new clientFrame();
client.setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==btn){
try{
InetAddress host = InetAddress.getByName(connection.getText());
socket = new Socket(host, 4567);
reader=new DataInputStream(socket.getInputStream());
writer=new PrintStream(socket.getOutputStream());
connected=true;
Thread thread=new Thread(this);
thread.start();
}catch(Exception se){
JOptionPane.showMessageDialog(null,"cannot connect");
socket=null;
reader=null;
writer=null;
}
connection.setText("");
}
if(e.getSource()==input){
if(writer!=null){
writer.println(input.getText());
getInfo(input.getText());
}
input.setText("");
}
}
///////////////
public void getInfo(String str){
StringBuffer temp=new StringBuffer(str+"\n");
temp.append(area.getText());
area.setText(temp.toString());
}
////////////
public void run(){
try{
while (true) {
// System.out.println("listenServer begin");
if(connected)
{String temp = reader.readLine();
getInfo(temp);}
//System.out.println("listen server have read a ");
}
}catch(Exception e){
JOptionPane.showMessageDialog(null,"server closed");
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -