看了毕老师的关于网络编程的视频后,
毕老师用UDP实现了用控制台进行聊天的小程序,
然后我就想把这个程序用GUI来实现而不是控制台,
写完后发现数据UDP打包了,但是不能显示在TextArea2的框框中,而且一点BUTTON程序就死了,
这是为啥。。。
上代码:可以直接运行,你们运行下看下是什么问题。
- <P>import java.awt.*;
- import java.awt.event.*;
- import java.io.*;
- import java.net.*;
- class UDPgui
- {
- private Frame f;
- private Button but;
- private TextArea ta1;
- private TextArea ta2;
- private Dialog d;
- private Button okBut;
- private Label la;
- public UDPgui()
- {
- init();
- }</P>
- <P> public void init()
- {
- f = new Frame("myFrame");
- f.setBounds(300,200,400,300);
- f.setLayout(new FlowLayout());</P>
- <P> but = new Button("提交");
- ta1 = new TextArea(6,50);
- ta2 = new TextArea(3,50);
- f.add(ta1);
- f.add(ta2);
- f.add(but);
- f.setVisible(true);</P>
- <P> d = new Dialog(f,"提示",true);
- d.setBounds(300,200,150,100);
- d.setLayout(new FlowLayout());
- okBut = new Button("确定");
- la = new Label();
- d.add(okBut);
- d.add(la);</P>
- <P> event();
- }</P>
- <P> private void event()
- {
- //匿名函数
- f.addWindowListener(
- new WindowAdapter()
- {
- public void windowClosing(WindowEvent e)
- {
- System.exit(0);
- }
- }
- );
- //匿名函数
- but.addActionListener(
- new ActionListener()
- {
- public void actionPerformed(ActionEvent e)
- {
- // System.out.println("按钮弹了一下");
- click();
- server();
- }
- }
- );</P>
- <P> //匿名函数
- okBut.addActionListener(
- new ActionListener()
- {
- public void actionPerformed(ActionEvent e)
- {
- d.setVisible(false);
- }
- }
- );</P>
- <P> //匿名函数
- d.addWindowListener(
- new WindowAdapter()
- {
- public void windowClosing(WindowEvent e)
- {
- d.setVisible(false);
- }
- }
- );
- }</P>
- <P> private void click()
- {
- DatagramSocket ds = null;
- try
- {
- ds = new DatagramSocket();
- String s = ta2.getText();
- byte[] b = s.getBytes();
- DatagramPacket dp =
- new DatagramPacket(b,b.length,InetAddress.getByName("192.168.1.255"),10001);</P>
- <P> ds.send(dp);
- System.out.print(s);
- }
- catch (Exception e)
- {
- throw new RuntimeException("发送失败");
- }
- finally
- {
- ds.close();
- }
- }</P>
- <P> private void server()
- {
- DatagramSocket ds = null;
- try
- {
- ds = new DatagramSocket(10001);
- byte[] by = new byte[1024*4];
- DatagramPacket dp = new DatagramPacket(by,by.length);
- ds.receive(dp);</P>
- <P> String ip = dp.getAddress().getHostAddress();
- String data = new String(dp.getData(),0,dp.getLength());</P>
- <P> ta1.append(ip+":"+data);
- }
- catch (Exception e)
- {
- throw new RuntimeException("接受失败");
- }
- finally
- {
- ds.close();
- }
- }</P>
- <P> public static void main(String[] args)
- {
- new UDPgui();
- }
- }</P>
- <P>
- </P>
复制代码 |