今天随手写了个很简单的聊天界面.该界面布局不是很好.实现简单的发送功能(现修改的) 有兴趣的可以加以完善,可以实现一下Socket. 代码如下: import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; //import java.net.*; //import java.util.*;
public class ChatClient extends JFrame { private JLabel l; private JButton b1; private JButton b2; JTextField jtf; JTextArea jta; private JPanel p1,p2; private int width; private int height; public ChatClient() { l=new JLabel("欢迎进入聊天室"); b1=new JButton("发送"); b2=new JButton("取消"); } public void launchFrame() { Container c=getContentPane(); c.setLayout(new BorderLayout()); p1=new JPanel(); p1.setLayout(new GridLayout(0,1)); p1.add(b1); p1.add(b2); p2=new JPanel(); p2.setLayout(new FlowLayout()); //p2.setBackground(Color.BLUE); p2.add(l); jta=new JTextArea(10,50); JScrollPane jp=new JScrollPane(jta); jtf=new JTextField(50); b1.addActionListener(new ActionListener() //对按钮b1的监听 { public void actionPerformed(ActionEvent e) { String s=jtf.getText(); jta.setText(jta.getText()+"\n"+s); jtf.setText(""); } }); b2.addActionListener(new ActionListener() //对按钮b2的监听 { public void actionPerformed(ActionEvent e) { System.exit(0); } }); jtf.addKeyListener(new KeyListener1()); c.add(jtf,BorderLayout.SOUTH); c.add(jp,BorderLayout.CENTER); c.add(p2,BorderLayout.NORTH); c.add(p1,BorderLayout.EAST); //jtf.addKeyListener(new KeyListener1()); } public static void main(String[] args) { ChatClient mf=new ChatClient(); mf.launchFrame(); mf.setTitle("欢迎来ChatRoom"); Toolkit t=Toolkit.getDefaultToolkit(); Dimension d=t.getScreenSize(); mf.setSize(d.width/2,d.height/2); mf.setLocation(d.width/4,d.height/4); mf.setBackground(Color.GRAY); //mf.setBounds(d.width/4,d.height/4,d.width/2,d.height/2);;; mf.setVisible(true); mf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } class KeyListener1 extends KeyAdapter //捕获键盘操作 { public void keyPressed(KeyEvent e) { int c=e.getKeyCode(); if(c==KeyEvent.VK_ENTER) { String s=jtf.getText(); jta.setText(jta.getText()+"\n"+s); jtf.setText(""); } } } }
[此贴子已经被作者于2005-8-19 0:51:32编辑过]