chatpanel.java

来自「jxme的一些相关程序,主要是手机上程序开发以及手机和计算机通信的一些程序资料,」· Java 代码 · 共 1,285 行 · 第 1/3 页

JAVA
1,285
字号
/*
 * Copyright (c) 2001 Sun Microsystems, Inc.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *       Sun Microsystems, Inc. for Project JXTA."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact Project JXTA at http://www.jxta.org.
 *
 * 5. Products derived from this software may not be called "JXTA",
 *    nor may "JXTA" appear in their name, without prior written
 *    permission of Sun.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL SUN MICROSYSTEMS OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of Project JXTA.  For more
 * information on Project JXTA, please see
 * <http://www.jxta.org/>.
 *
 * This license is based on the BSD license adopted by the Apache Foundation.
 *
 * $Id: ChatPanel.java,v 1.8 2002/05/15 23:39:45 chaywood Exp $
 *
 */

package net.jxta.j2me.demo.chat;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Container;
import java.awt.Choice;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Label;
import java.awt.List;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.event.TextListener;
import java.awt.event.TextEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Vector;
import java.awt.image.ImageObserver;
import java.awt.Image;
import java.awt.Dimension;

import net.jxta.j2me.PeerNetwork;
import net.jxta.j2me.Message;
import net.jxta.j2me.Element;

public class ChatPanel extends Panel implements ActionListener, 
        ItemListener, KeyListener, Runnable {

    public static final boolean DEBUG = false;
    public static final boolean WARN = true;

    public static final String TITLE_BUDDY     = "Chat";
    public static final String TITLE_SETTINGS  = "Settings";
    public static final String TITLE_ADMIN     = "Buddies";
    public static final String TITLE_ADD       = "Find";

    public static final String BUTTON_BUDDIES = "Buddies...";
    public static final String BUTTON_SETTINGS = "Settings...";
    public static final String BUTTON_REMOVE = "Remove";
    public static final String BUTTON_ADDING    = "Add...";
    public static final String BUTTON_DONE   = "Done";
    public static final String BUTTON_SEARCH   = "Search";
    public static final String BUTTON_CANCEL   = "Cancel";
    public static final String BUTTON_ADD    = "Add";
    public static final String BUTTON_SEND   = "Send";
    public static final String BUTTON_IMAGE   = "Image";
    public static final String BUTTON_BYE    = "Bye";
    public static final String BUTTON_OK    = "Ok";

    // default colors
    public static final Color DEFAULT_PANEL_FG = null; // Color.blue;
    public static final Color DEFAULT_PANEL_BG = null; // Color.green;
    public static final Color DEFAULT_TEXTCOMPONENT_BG = null; // Color.red;
    public static final Color DEFAULT_BUTTON_BG = null; // Color.orange;

    static final String[] CANNED_PHRASES = { "Hello!", "Goodbye!", 
                                             "I'm Home.", "I'm at Work.", 
                                             "Where are you?", "What time?", 
                                             "Where?", "------------", 
                                             "Customize...", "Send picture..." };
    static final int NUMBER_PHRASES = 7;

    public static final String DEFAULT_RELAY = "http://209.25.154.233:9700";

    public static final String CHAT_USERNAME_PREFIX = "JxtaTalkUserName.";

    public static final String PIPE_TYPE_UNICAST = "JxtaUnicast";
    public static final String PIPE_TYPE_PROPAGATE = "JxtaPropagate";

    static final String ID_PREFIX       = "urn:jxta:uuid-";
    static final String WORLD_GROUP_ID  = "59616261646162614A78746150325033";
    static final String NET_GROUP_ID    = "59616261646162614E50472050325033";

    static final String GROUP_ID_SUFFIX = "02";
    static final String PEER_ID_SUFFIX  = "03";
    static final String PIPE_ID_SUFFIX  = "04";

    static final int UUID_START_INDEX = 37;
    static final int UUID_END_INDEX = UUID_START_INDEX + 32;

    static final String IP2PGRP_NAME = "IP2PGRP";
    static final String IP2PGRP_ID = ID_PREFIX + NET_GROUP_ID + 
                                     "D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1" + 
                                     PIPE_ID_SUFFIX;
    static final String IP2PGRP_TYPE = PIPE_TYPE_PROPAGATE;
    static final String IP2PGRP_GROUP = "NetPeerGroup";
    static final Destination IP2PGRP = new Destination(IP2PGRP_NAME, 
                                                       IP2PGRP_ID, 
                                                       IP2PGRP_TYPE, 
                                                       IP2PGRP_GROUP);

    static final String PICSHAREGRP_NAME = "PicShare";
    static final String PICSHAREGRP_ID = ID_PREFIX + NET_GROUP_ID + 
                                         "50696353686172652D5B46696C654361" +
                                         PIPE_ID_SUFFIX;
    static final String PICSHAREGRP_TYPE = PIPE_TYPE_PROPAGATE;
    static final String PICSHAREGRP_GROUP = "NetPeerGroup";
    static final Destination PICSHAREGRP = new Destination(PICSHAREGRP_NAME, 
                                                           PICSHAREGRP_ID, 
                                                           PICSHAREGRP_TYPE, 
                                                           PICSHAREGRP_GROUP);
    private PeerNetwork peer;
    private Destination user;
    private String peerId = "";
    private Thread thread = null;
    private Destination currentBuddy = null;
    private Vector buddyList = new Vector();
    private Vector resultList = new Vector();
    private boolean isMessengerPanel = false;

    // The Chat Widget Panels
    private BuddyPanel buddyPanel;
    private BuddyAdminPanel buddyAdminPanel;
    private BuddyAddPanel buddyAddPanel;
    private MessengerPanel messengerPanel;
    private SettingsPanel settingsPanel;
    private ImageViewPanel imagePanel;

    public ChatPanel() {
        buddyPanel = new BuddyPanel();
        buddyAdminPanel = new BuddyAdminPanel();
        buddyAddPanel = new BuddyAddPanel();
        messengerPanel = new MessengerPanel();
        settingsPanel = new SettingsPanel();
        imagePanel = new ImageViewPanel();

        setRelay(DEFAULT_RELAY);

        user = new Destination("", "", PIPE_TYPE_UNICAST, "");

        // set the color
        if (DEFAULT_PANEL_FG != null) {
            setForeground(DEFAULT_PANEL_FG);
        }

        if (DEFAULT_PANEL_BG != null) {
            setBackground(DEFAULT_PANEL_BG);
        }

        setLayout(new BorderLayout());

        buddyPanel.buddyList.addItemListener(this);
        buddyPanel.buddiesButton.addActionListener(this);
        buddyPanel.settingsButton.addActionListener(this);

        messengerPanel.sendButton.addActionListener(this);
        messengerPanel.imageButton.addActionListener(this);
        messengerPanel.byeButton.addActionListener(this);
        messengerPanel.inputField.addKeyListener(this);

        buddyAdminPanel.removeButton.addActionListener(this);
        buddyAdminPanel.addButton.addActionListener(this);
        buddyAdminPanel.doneButton.addActionListener(this);

        buddyAddPanel.searchButton.addActionListener(this);
        buddyAddPanel.cancelButton.addActionListener(this);
        buddyAddPanel.addButton.addActionListener(this);

        settingsPanel.doneButton.addActionListener(this);
        settingsPanel.doneButton.setEnabled(false);

        imagePanel.okButton.addActionListener(this);

        addBuddy(IP2PGRP);
        addBuddy(PICSHAREGRP);

        selectPanel(settingsPanel, TITLE_SETTINGS);
    }

    public ChatPanel(String relay, String peerId, 
                     Destination user, Vector buddies) {
        this();

        setUser(user);
        setRelay(relay);
        setPeerId(peerId);

        for (Enumeration e = buddies.elements(); e.hasMoreElements(); ) {
            addBuddy((Destination)e.nextElement());
        }

        if (user.name.length() == 0) {
            selectPanel(settingsPanel, TITLE_SETTINGS);
        } else {
            settingsPanel.doneButton.setEnabled(true);
            selectPanel(buddyPanel, TITLE_BUDDY);

            connect();
        }
    }
    public void actionPerformed(ActionEvent evt) {
        if (DEBUG) {
            System.out.println("actionPerformed " + evt);
        }

        // actions from the Buddy Panel
        if (evt.getSource() == buddyPanel.buddiesButton) {
            selectPanel(buddyAdminPanel, TITLE_ADMIN);
        } else if (evt.getSource() == buddyPanel.settingsButton) {
            selectPanel(settingsPanel, TITLE_SETTINGS);

        // actions from the Messenger Panel
        } else if (evt.getSource() == messengerPanel.sendButton) {
            sendMessage();
        } else if (evt.getSource() == messengerPanel.byeButton) {
            if (PIPE_TYPE_PROPAGATE.equals(currentBuddy.type)) {
                try {
                    // start listening on group pipe
                    peer.close(CHAT_USERNAME_PREFIX+currentBuddy.name, 
                                currentBuddy.id, currentBuddy.type);

                    thread.interrupt();
                } catch (Exception e) {
                    if (DEBUG) {
                        System.out.println("status: could not close group pipe");
                    }
                }
            }

            messengerPanel.logArea.setText("");
            messengerPanel.inputField.setText("");

            selectPanel(buddyPanel, TITLE_BUDDY);

        // actions from the Buddy Admin Panel
        } else if (evt.getSource() == buddyAdminPanel.removeButton) {
            int[] indexes = buddyAdminPanel.buddyList.getSelectedIndexes();

            for (int i = indexes.length-1; i >= 0; i--) {
                if (DEBUG) {
                    System.out.println("remove buddy at index " + indexes[i]);
                }
                buddyPanel.buddyList.remove(indexes[i]);
                buddyAdminPanel.buddyList.remove(indexes[i]);
                buddyList.removeElementAt(indexes[i]);
            }
        } else if (evt.getSource() == buddyAdminPanel.addButton) {
            selectPanel(buddyAddPanel, TITLE_ADD);
        } else if (evt.getSource() == buddyAdminPanel.doneButton) {
            selectPanel(buddyPanel, TITLE_BUDDY);

        // actions from the Buddy Add Panel
        } else if (evt.getSource() == buddyAddPanel.searchButton) {
            search();
        } else if (evt.getSource() == buddyAddPanel.cancelButton) {
            selectPanel(buddyAdminPanel, TITLE_ADMIN);
        } else if (evt.getSource() == buddyAddPanel.addButton) {
            int[] indexes = buddyAddPanel.resultList.getSelectedIndexes();

            for (int i = 0; i < indexes.length; i++) {
                addBuddy((Destination)resultList.elementAt(indexes[i]));
            }

            selectPanel(buddyAdminPanel, TITLE_ADMIN);

        // actions from the Settings Panel
        } else if (evt.getSource() == settingsPanel.doneButton) {
            user.name = settingsPanel.userField.getText();
            setUser(user);

            setRelay(settingsPanel.relayField.getText());

            selectPanel(buddyPanel, TITLE_BUDDY);

            connect();

        } else if (evt.getSource() == imagePanel.okButton) {
            selectPanel(messengerPanel, "Chat group " + currentBuddy.name);
        } else if (evt.getSource() == messengerPanel.imageButton) {
            selectPanel(imagePanel, "Picshare with " + currentBuddy.name);
        }
    }

    public void itemStateChanged(ItemEvent evt) {
        if (DEBUG) {
            System.out.println("itemStateChanged " + evt);
        }

        if (evt.getSource() == buddyPanel.buddyList) {
            currentBuddy = getBuddy(buddyPanel.buddyList.getSelectedIndex());

            if (DEBUG) {
                System.out.println("currentBuddy name=" + currentBuddy.name + 
                                   " id=" + currentBuddy.id + 
                                   " type=" + currentBuddy.type + 
                                   " group=" + currentBuddy.group);
            }

            if (PIPE_TYPE_PROPAGATE.equals(currentBuddy.type)) {
                try {
                    // start listening on group pipe
                    peer.listen(CHAT_USERNAME_PREFIX+currentBuddy.name, 
                                currentBuddy.id, currentBuddy.type);

                    selectPanel(messengerPanel, "Chat group " + currentBuddy.name);
                } catch (Exception e) {
                    if (WARN) {
                        System.err.println("status: could not listen to group pipe");
                    }
                }
            } else {
                selectPanel(messengerPanel, "Chat with " + currentBuddy.name);
            }

            int index = buddyPanel.buddyList.getSelectedIndex();
            if (index != -1) {
                buddyPanel.buddyList.deselect(index);
            }

            // make sure we are listen to our user pipe
            try {
                // start listening on user pipe
                peer.listen(CHAT_USERNAME_PREFIX+user.name, user.id, user.type);

                thread.interrupt();
            } catch (Exception e) {
                if (WARN) {
                    System.err.println("status: could not listen to user pipe");
                }
            }

        }
    }

    public void keyTyped(KeyEvent evt) {}
    public void keyReleased(KeyEvent evt) {}
    public void keyPressed(KeyEvent evt) {
        if (evt.getSource() == messengerPanel.inputField && 
            evt.getKeyCode() == KeyEvent.VK_ENTER) {
            sendMessage();
        }
    }

    private void selectPanel(Panel selectedPanel, String title) {
        Container parent = getParent();

        isMessengerPanel = selectedPanel == messengerPanel;

        if (DEBUG) {
            System.out.println("parent = " + parent);
        }
        if (parent instanceof Frame) {
            if (DEBUG) {
                System.out.println("parent is a frame");
            }
            ((Frame)parent).setTitle(title);
        }

        removeAll();

        add(selectedPanel, BorderLayout.CENTER);

        if (getParent() != null) {
            getParent().validate();
        }
    }

    static class BuddyPanel extends Panel {
        List buddyList = new List();

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?