⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 chatapplet.java

📁 一款用JAVA制作开发的小型聊天软件
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
 */

  public int getDefaultPort() {
    try {
      return getParameter("Port") != null && new Integer(getParameter("Port")).intValue() > 2048 ? new Integer(getParameter("Port")).intValue() : DEFAULT_PORT;
    }
    catch (NumberFormatException excpt) {
      return DEFAULT_PORT;
    }
  }


/**
 * Returns the ChatClient.
 */

  public ChatClient getClient() {
    return chatClient;
  }


/**
 * Requests that the browser or applet viewer show the Web page indicated by the
 * url argument.
 *
 * @param url         an absolute URL giving the location of the document
 * @param target      a String indicating where to display the page
 */

  public void showDocument(URL url, String target) {
    getAppletContext().showDocument(url, target);
  }


/**
 * Returns the Id of the current Room.
 */

  public synchronized int getCurrentRoomId() {
    try {
      return getCurrentUser().getRoom();
    }
    catch (Exception excpt) {
      return 0;
    }
  }


/**
 * Returns the current Room.
 */

  public synchronized Room getCurrentRoom() {
    return getRoom(getCurrentUser().getRoom());
  }


/**
 * Sets the Id of the current Room.
 *
 * @param roomIdParam      the Id of the current Room
 */

  public synchronized void setCurrentRoomId(int roomIdParam) {
    moveUserToRoom(getCurrentUserId(), roomIdParam, isConnected());
  }



/**
 * Returns the Room with a certain id.
 *
 * @param idParam      the Room's id
 */

  public synchronized Room getRoom(int idParam) {
    Object object;
    object = roomTable.get(idParam);
    if (object != null)
      return (Room)object;
    else
      return null;
  }


/**
 * Returns an Enumeration of the Rooms' Ids.
 */

  public synchronized Enumeration getRoomIds() {
    return roomTable.keys();
  }


/**
 * Returns a Rooms' Users' Ids as a Vector.
 *
 * @param roomId      the Room's id
 */

  public synchronized Vector getRoomUserIdVector(int roomId) {
    Room room;
    Vector roomUserIdVector;
    Enumeration userNameEnum;

    roomUserIdVector = new Vector();

    if ((room = getRoom(roomId)) != null) {
      userNameEnum = room.getUserNameVector().elements();

      while (userNameEnum.hasMoreElements()) {
        roomUserIdVector.addElement(new Integer(getUserId((String)userNameEnum.nextElement())));
      }
    }
    return roomUserIdVector;
  }


  public synchronized int getUserId(String userNameParam) {
    Enumeration userIdEnum;
    int id;

    userIdEnum = userTable.keys();

    while (userIdEnum.hasMoreElements()) {
      if (((User)userTable.get(id = ((Integer)userIdEnum.nextElement()).intValue())).getName().equals(userNameParam))
        return id;
    }

    return -1;
  }



/**
 * Moves a User to a Room.
 *
 * @param userIdParam      the Id of the User to be moved
 * @param roomIdParam      the Id of the Room to move the User to
 */

  public synchronized void moveUserToRoom(int userIdParam, int roomIdParam, boolean send) {
    Room room;
    User user;
    boolean bGenerateHistoryEntry, bRestartHistory;

    if (userTable.containsKey(userIdParam) && roomTable.containsKey(roomIdParam)) {
      room = getRoom(roomIdParam);
      user = getUser(userIdParam);
      if (room.hasAccess(user.getName())) {

        bRestartHistory = (user.getRoom() == getCurrentRoomId() && roomIdParam != getCurrentRoomId());
        bGenerateHistoryEntry = (user.getRoom() == getCurrentRoomId() || roomIdParam == getCurrentRoomId());

        if (getRoom(getUser(userIdParam).getRoom()) != null) {
          getRoom(user.getRoom()).removeUser(user.getName());
        }

        user.setRoom(roomIdParam);
        room.addUser(user.getName());

        if (userIdParam == getCurrentUserId()) {
          setStatus("Joined room \"" + room.getName() +"\"");
          if (bRestartHistory) {
            restartHistory();
          }
          if (send)
            chatClient.send(new UserRoomEvent(userIdParam, roomIdParam, new Point()));
        }

        repaintView();
        repaintRoom();
        updateRoomList();

        if (bGenerateHistoryEntry)
          generateHistoryEntry();

      }
      else if (userIdParam == getCurrentUserId()) {
        setStatus("You do not have access to room \"" + room.getName() +"\"");
      }
    }
  }


/**
 * Returns the number of Rooms.
 */

  public synchronized int getNrOfRooms() {
    return roomTable.size();
  }


/**
 * Returns the Id of a Room of a given name.
 */

  public synchronized int getRoomId(String roomNameParam) {
    Enumeration roomIds;
    int roomId;

    roomIds = getRoomIds();
    while (roomIds.hasMoreElements()) {
      roomId = ((Integer)roomIds.nextElement()).intValue();
      if (getRoom(roomId).getName().equals(roomNameParam))
        return roomId;
    }
    return -1;
  }

  public byte[] getResourceFromArchive(String strResource) {
    InputStream inStr;
    byte[] buffer;

    try {
      inStr = getClass().getResourceAsStream(strResource);
      if (inStr == null) {
        return null;
      }
      buffer = new byte [inStr.available()];
      inStr.read(buffer);
      return buffer;
    }
    catch (IOException excpt) {
      excpt.printStackTrace();
    }
    return null;
  }
/**
 * Retrieves an image from the webserver.
 *
 * @param name      the file name
 */

  public Image getImage(String name, boolean wait) {
    Image img;
    byte buffer[] = getResourceFromArchive("/" + IMAGE_FOLDER + name);
    if (buffer != null) {
      img =  Toolkit.getDefaultToolkit().createImage(buffer);
    }
    else {
      img = getImage(getCodeBase(), IMAGE_FOLDER + name);
    }
    if (wait) {
      if (tracker == null) {
        tracker = new MediaTracker(this);
      }
      tracker.addImage(img, 0);
      try {
        tracker.waitForID(0, 5000);
      }
      catch (InterruptedException excpt) {
        excpt.printStackTrace();
      }
    }
    return img;
  }

  public Image getImage(String name) {
    return getImage(name, false);
  }

/**
 * Displays another User's data in a new Frame.
 *
 * @param userId      the Id of the User to be shown
 */

  public void showUser(int userIdParam) {
    if (chatFrame != null)
      chatFrame.showUser(userIdParam);
  }


/**
 * Updates User data in the User TabPanel, which can be edited.
 *
 * @param userId      the Id of the User to be edited
 */

  public void editUser(int userIdParam) {
    if (chatFrame != null)
      chatFrame.editUser(userIdParam);
  }


/**
 * Displays a Room's data in a new Frame.
 *
 * @param roomId      the Id of the Room to be shown
 */

  public void showRoom(int roomIdParam) {
    if (chatFrame != null)
      chatFrame.showRoom(roomIdParam);
  }


/**
 * Updates Room data in the Room TabPanel, which can be edited by the Room's
 * Administrator.
 *
 * @param userId      the Id of the Room to be edited
 */

  public void editRoom(int roomIdParam) {
    if (chatFrame != null)
      chatFrame.editRoom(roomIdParam);
  }


/**
 * Creates a new Room and lets the User edit its data.
 */

  public synchronized void createRoom() {
    Room room;
    int roomId;

    roomId = isConnected() ? NEW_ROOM_ID : getNrOfRooms();
    room = new Room(roomId, "New Room", ROOM_DIMENSION);
    if (roomExists(room.getName())) {
      int i;
      for (i = 1; roomExists(room.getName() + i); i++);
      room.setName(room.getName() + i);
    }
    room.setAdministrator(getCurrentUser().getName());
    room.setDemo(!isConnected());
    addRoom(room);
    moveUserToRoom(getCurrentUserId(), roomId, false);
    if (chatFrame != null)
      chatFrame.editRoom(roomId);
  }


/**
 * Repaint the current User. Should be called after his data has been updated.
 * Administrator.
 */

  public void repaintCurrentUser() {
    if (chatFrame != null)
      chatFrame.repaintCurrentUser();
  }


/**
 * Returns the Room with a certain name.
 *
 * @param roomNameParam      the Rooms's name
 */

  public Room getRoom(String roomNameParam) {
    return getRoom(getRoomId(roomNameParam));
  }


/**
 * Returns true if a Room of a certain name exists.
 *
 * @param roomNameParam      the Name of the Room
 */

  public boolean roomExists(String roomNameParam) {
    return getRoom(roomNameParam) != null;
  }


/**
 * Returns true if the ChatClient is currently connected to a ChatServer.
 */

  public boolean isConnected() {
    return chatClient != null && chatClient.connected();
  }


/**
 * Defines the ChatApplet's HistoryPanel. This Panel will receive
 * MessageEntries.
 *
 * @param pnlHistoryParam      the ChatApplet's HistoryPanel
 */

  public void setHistoryPanel(HistoryPanel pnlHistoryParam) {
    pnlHistory = pnlHistoryParam;
  }


/**
 * Returns an Image being used as the slider in the HistoryPanel's scrollbar.
 * MessageEntries.
 */

  public Image getSliderImage() {
    return imgSlider;
  }


/**
 * Brings the Chat TabPanel back to the foreground.
 */

  public void showChat() {
    if (chatFrame != null)
      chatFrame.showChat();
  }


/**
 * Stores the Chat's current situation into the history.
 */

  private synchronized void generateHistoryEntry() {
    hashHistory.put(new Date(), getCurrentSituationVector());
  }


/**
 * Returns a Vector which reflects the Chat's current situation.
 */

  public synchronized Vector getCurrentSituationVector() {
    Vector vecHistoryEntry, vecCurrentRoomUserIds;
    Date dateNow;
    User user;

    dateNow = new Date();
    vecHistoryEntry = new Vector();
    vecCurrentRoomUserIds = getRoomUserIdVector(getCurrentRoomId());
    for (int i = 0; i < vecCurrentRoomUserIds.size(); i++) {
      user = getUser(((Integer)vecCurrentRoomUserIds.elementAt(i)).intValue());
      if (user != null)
        vecHistoryEntry.addElement(new HistoryEntry(dateNow, getCurrentRoomId(), user.getId(), user.getPosition(), user.getHeading(), user.getColor(), user.getMessage(), user.getMood()));
    }
    return (Vector)vecHistoryEntry.clone();
  }


/**
 * Returns a Vector which reflects the Chat's situation at a certain point in time.
 *
 * @param dateParam      the Date to return the Vector for
 */

  public synchronized Vector getHistoryEntryVector(Date dateParam) {
    Object objHistory;
    HistoryEntry histEntry;
    Date date, dateEntry;
    Enumeration enumDate;

    date = new Date(0l);
    enumDate = hashHistory.keys();

    while (enumDate.hasMoreElements()) {
      dateEntry = (Date)enumDate.nextElement();
      if (dateEntry.getTime() < dateParam.getTime() && dateEntry.getTime() > date.getTime())
        date = dateEntry;
    }

    return ((objHistory = hashHistory.get(date)) != null) ? (Vector)(((Vector)objHistory)).clone() : new Vector();
  }


/**
 * Restarts the Chat's history.
 */

  public synchronized void restartHistory() {
    hashHistory = new Hashtable();
    if (pnlHistory != null)
      pnlHistory.clear();
  }


/**
 * Runs a Thread being used to timeout User moods.
 */

  public void run() {
    try {
      Thread.sleep(getCurrentUser().getMoodTimeout() * 1000);
    }
    catch (InterruptedException excpt) {
    }
    finally {
      setUserMood(getCurrentUserId(), 0, isConnected());
    }
  }


/**
 * Returns an incidently chosen User.
 */

  public User getRandomUser() {
    Vector roomUserIdVector;
    roomUserIdVector = getRoomUserIdVector(getCurrentRoomId());
    return getUser(((Integer)roomUserIdVector.elementAt((int)(roomUserIdVector.size() * new Random().nextFloat()))).intValue());
  }


/**
 * Returns the TK-Logo.
 */

  public ImageCanvas getLogo() {
    return (ImageCanvas)logoCanvas.clone();
  }


/**
 * Returns the default avatar for a certain mood.
 *
 * @param moodParam        the User's mood
 */

  public Image getDefaultAvatar(int moodParam) {
    return (moodParam >= 0 && moodParam < PREDEFINED_NR_OF_MOODS) ? defaultAvatar[moodParam] : null;
  }


/**
 * Returns the default back-side avatar.
 */

  public Image getDefaultBackAvatar() {
    return defaultBackAvatar;
  }

  public synchronized void setRoomTable(IntegerHashtable roomTableParam) {
    Room room;
    room = (Room)roomTable.get(0);
    roomTable = roomTableParam;
    roomTable.put(0, room);
    moveUserToRoom(getCurrentUserId(), 0, false);
    fillRoomList();
    repaintAll();
  }

}


⌨️ 快捷键说明

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