GUI和网络编程
一、图形化界面
a) GUI概念:Graphical User Interface图形化用户界面
1. AWT和SWING:awt依赖于本地系统平台,swing跨平台
2. 组件和容器:
1. 组件:Component是GUI图形界面的组成元素
2. 容器:Container可以存放组件,也可以存放容器
b) 布局管理
1. FlowLayout(流式布局管理器)
2. BorderLayout(边界布局管理器)
3. GridLayout(网格布局管理器)
4. CardLayout(卡片布局管理器)
5. GridBagLayout(网格包布局管理器)
c) 建立一个窗体
1. 构造一个窗体Frame frame = new Frame();
2. 设置可见:frame.setVisible(true);
3. 设置大小:frame.setSize(400,300);
4. 设置位置:frame.setLocation();
5. 设置标题:frame.setTitle(“哈哈”);
6. 设置图标:frame.setIconImage(Toolkit.getDefaultTookit().createImage(“qq.png”));
7. 创建按钮:Button btn = new Button(“关闭”);
8. 将按钮放入窗体:frame.add(btn);
9. 设置布局:frame.setLayout(new FlowLayout())
d) 事件处理
1. 事件概念:用户对程序的操作
2. 添加窗体监听器:frame.addWindowListener();
3. 窗体适配器:
1. 激活:windowActivated(){}
2. 已关闭:windowClosed(){}
3. 正在关闭:windowClosing(){}
4. 不是活动的:windowDeactivated(){}
5. 已打开:windowOpened(){}
6. 最小化:windowIconified(){}
7. 从最小化恢复:windowDeiconified(){}
4. 鼠标适配器:
1. 点击:mouseClicked(){}
2. 鼠标进入组件:mouseEntered(){}
3. 鼠标离开组件:mouseExited(){}
4. 按下鼠标:mousePressed(){}
5. 鼠标弹起:mouseReleased(){}
二、网络编程
1.UDP无连接,不区分客户端与服务器
DatagramSocket socket=new DatagramSocket();
DatagramPacket pack=new DatagramPacket(数据,数据长度,ip地址,端口号);
socket.send(pack);//发送数据
或者socket.receive();//接受数据,使用getDate(),getLength()获取数据
2.TCP有连接,区分客户端和服务器
客户端socket(服务器ip,服务器端口号);
服务器ServerSocket(端口号);
服务器通过accpet()连接,两边通过getInputStream(),getOutputStream()进行读写。也可以通过getPort(),getInetAddress().getHostAddress()获得端口号和IP。
3.练习
public class Excise3chats1 {Frame f =new Frame("聊天室");
Panel p1=new Panel();
Panel p2=new Panel();
TextArea text1=new TextArea();
TextArea text2=new TextArea(5,3);
TextField tf=new TextField(15);
Button sendButton=new Button("发送");
Button clsButton=new Button("清除");
Button chatButton=new Button("聊天记录");
Button shakeButton=new Button("震动");
Lock lock=new ReentrantLock();
DatagramSocket socket;
Writer writer;
public Excise3chats1() {
generateGUI();
handleEvent();
new ReceiveThread().start();
// TODO Auto-generated constructor stub
}
private void handleEvent() {
// TODO Auto-generated method stub
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
// TODO Auto-generated method stub
try {
socket.close();
writer.close();
f.dispose();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}finally{
System.exit(0);
}
}
});
sendButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
send();
}
});
text2.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if(e.getKeyCode()==KeyEvent.VK_ENTER)
{
send();
e.consume();
}
}
});
clsButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
text1.setText("");
}
});
chatButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try {
writer.flush();
BufferedReader read=new BufferedReader(new FileReader("log.txt"));
System.out.println("sdfs");
String line;
while((line=read.readLine())!=null){
System.out.println("d");
text1.append(line+"\r\n");
System.out.println("e");
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
shakeButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String ip=tf.getText();
DatagramSocket socket;
try {
socket = new DatagramSocket();
DatagramPacket packet=new DatagramPacket(new byte[]{-1},new byte[]{-1}.length,InetAddress.getByName(ip),8888);
socket.send(packet);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
}
private void send() {
// TODO Auto-generated method stub
String ip=tf.getText();
String smg=text2.getText();
ip="".equals(ip)?"255.255.255.255":ip;
if(smg.length()==0)
return;
String regexPart="(\\d)|(\\d{2})|([01]\\d{2})|(2[0-4]\\d)|(25[0-5])";
String ipRegex=regexPart+"\\."+regexPart+"\\."+regexPart+"\\."+regexPart;
if(!ip.matches(ipRegex))
return;
try {
socket=new DatagramSocket();
DatagramPacket packet=new DatagramPacket(smg.getBytes(),smg.getBytes().length,InetAddress.getByName(ip),8888);
lock.lock();
socket.send(packet);
String date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
String content=date+"我向"+ip+"发送"+"\r\n"+smg+"\r\n\r\n";
text1.append(content);
writer.write(content);
text2.setText("");
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
lock.unlock();
}
}
private void generateGUI() {
f.setSize(400, 600);
f.setLocation(300, 50);
f.setIconImage(Toolkit.getDefaultToolkit().createImage("1.png"));
f.setLayout(new BorderLayout());
text1.setEditable(false);
text1.setBackground(Color.white);
tf.setText("255.255.255.255");
p1.setLayout(new BorderLayout());
p1.add(text1,BorderLayout.CENTER);
p1.add(text2,BorderLayout.SOUTH);
//
p2.setLayout(new FlowLayout());
p2.add(tf);
p2.add(sendButton);
p2.add(clsButton);
p2.add(chatButton);
p2.add(shakeButton);
f.add(p1,BorderLayout.CENTER);
f.add(p2,BorderLayout.SOUTH);
// p1.setVisible(true);
// p2.setVisible(true);
f.setVisible(true);
try {
writer=new BufferedWriter(new FileWriter("log.txt"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new Excise3chats1();
}
class ReceiveThread extends Thread{
public void run(){
try {
DatagramSocket rsocket=new DatagramSocket(8888);
DatagramPacket rpacket=new DatagramPacket(new byte[1024],1024);
while(true){
rsocket.receive(rpacket);
if(rpacket.getLength()==1 && rpacket.getData()[0]==-1){
doShake();
continue;
}
String rsmg=new String(rpacket.getData(),0,rpacket.getLength());
String date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
String rip=rpacket.getAddress().getHostAddress();
String content=date+"我收到"+rip+"的消息"+"\r\n"+rsmg+"\r\n\r\n";
lock.lock();
try{
text1.append(content);
writer.write(content);
}finally{
lock.unlock();
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void doShake() {
// TODO Auto-generated method stub
int x=f.getLocation().x;
int y=f.getLocation().y;
f.toFront();
f.setVisible(true);
try {
f.setLocation(x-20, y-20);
Thread.sleep(20);
f.setLocation(x+20, y+20);
Thread.sleep(20);
f.setLocation(x+20, y-20);
Thread.sleep(20);
f.setLocation(x-20, y+20);
Thread.sleep(20);
f.setLocation(x-20, y-20);
Thread.sleep(20);
f.setLocation(x, y);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}