JFrame,JPanel,JLabel学习

JFrame是一个顶层的框架类,好比一个窗户的框子。也是一个容器类。这个框子可以嵌入几个玻璃窗。

JPanel是一个容器类,相当于一大玻璃窗。

JLabel等是一些基础组件,它必须置于某个容器里,类似于窗花、剪纸,必须置于窗户的表面。

public class Server extends JFrame implements Runnable{
    private Socket s = null;
    private ServerSocket ss = null;
    private JTextField jtf = new JTextField();
    private JTextArea jta = new JTextArea();

    private ArrayList<ChatThread>clients = new ArrayList<ChatThread>();
    public Server() throws Exception{
        this.setTitle("服务器端");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.add(jta,BorderLayout.CENTER);
        jta.setBackground(Color.yellow);
        this.setSize(400,200);
        this.setVisible(true);
        ss = new ServerSocket(9999);
        new Thread(this).start();
    }
public void run(){
        try{
            while(true){
                s = ss.accept();
                ChatThread ct = new ChatThread(s);
                clients.add(ct);
                ct.start();
            }
        }catch (Exception ex){
            ex.printStackTrace();
            javax.swing.JOptionPane.showMessageDialog(this,"游戏异常退出!");
            System.exit(0);

        }
    }

    class ChatThread extends Thread{
        private Socket s = null;
        private BufferedReader br = null;
        private PrintStream ps = null;
        private boolean canRun = true;
        public ChatThread(Socket s)throws Exception{
            this.s = s;
            br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            ps = new PrintStream(s.getOutputStream());
        }
        public void run(){
            try{
                while (canRun){
                    String str = br.readLine();
                    sendMessage(str);

                }
        }catch (Exception ex){
                canRun = false;
                clients.remove(this);
            }
        }
    }

    public void sendMessage(String msg){
        for(ChatThread ct:clients){
            ct.ps.println(msg);
        }
    }

    public static void main(String[] args)throws Exception{
        Server server = new Server();
    }

}

这里写代码片
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值