📄 chatroompanel.java
字号:
/** * Asks for a new nickname, and sends a nickname change request */ private void changeNickHandler() { String result = (String) JOptionPane.showInputDialog(null, resources .getString("enterNickname"), resources.getString("setNickname"), JOptionPane.QUESTION_MESSAGE, null, null, chat.getNickname()); if (result != null && !result.equals("")) { Thread thread = new Thread(new RunTaskThread(resources .getString("couldNotChangeNick"), "changeNickname", result)); thread.start(); } } /** * Adds the event listeners for the various components in this chatwindows */ public void addListeners() { //set up the window so you can press enter in the text box and //that will send the message. Action SendMessageAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { sendHandler(); } }; Action nickCompletionAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { nickCompletionHandler(); } }; //set it up so that if they drag in the conversation window, it grabs // the focus conversationArea.addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { conversationArea.grabFocus(); } }); //set it up so that if there isn't any selected text in the // conversation area //the textentryarea grabs the focus. conversationArea.addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { if (conversationArea.getSelectedText() == null) { textEntryArea.requestFocus(); } else conversationArea.grabFocus(); } public void focusLost(FocusEvent e) { } }); Action closeAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { BuddyList.getInstance().getTabFrame().removePanel(thisPointer); BuddyList.getInstance().stopTabFrame(); } }; subjectField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { subjectField.setEnabled(false); topicHandler(subjectField.getText()); setSubject(subject); } }); KeyStroke enterStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0); textEntryArea.getInputMap().put(enterStroke, SendMessageAction); KeyStroke tabStroke = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0); textEntryArea.getInputMap().put(tabStroke, nickCompletionAction); textEntryArea.getInputMap().put( KeyStroke.getKeyStroke(KeyEvent.VK_W, Toolkit .getDefaultToolkit().getMenuShortcutKeyMask()), closeAction); } /** * Leaves this room and removes it from the groupchat frame */ public void leave() { closeLog(); leaveChat(); } //leave the chatroom /** * Gets the nickname currently being used in the chat room * * @return the nickname being used in the chatroom */ public String getNickname() { if (chat == null || chat.getNickname() == null) return nickname; return chat.getNickname(); } /** * Displays a server notice message * * @param message * the message to display */ public void serverNoticeMessage(String message) { conversationArea.append("" + getDate(null) + "<font color='green'> -> " + message + "</font>"); } public void serverErrorMessage(String message) { conversationArea.append("" + getDate(null) + "<font color='maroon'> -> " + message + "</font>"); } /** * Receives a message * * @param from * who it's from * @param message * the message */ public synchronized void receiveMessage(String from, String message, Date date) { message = ConversationText.replaceText(message, false); //replace // emoticons, // links, etc... String curNick = nickname; if( chat != null ) curNick = chat.getNickname(); if (from.equals("") || from.toLowerCase().equals(chat.getRoom().toLowerCase())) { //server message serverNoticeMessage(message); return; } else { boolean highLightedSound = false; if (message.startsWith(" /me ")) { message = message.replaceAll("^ \\/me ", ""); conversationArea.append("" + getDate(date) + " <b><font color='maroon'>* " + from + "</font></b> " + message ); } else if (message.toLowerCase().replaceAll("<[^>]*>", "").matches( ".*(^|\\W)" + curNick.toLowerCase() + "\\W.*")) { TabbedPanel tabPane = BuddyList.getInstance().getTabFrame() .getTabPane(); if (tabPane.getSelectedTab().getContentComponent() != this) messageToMe = true; conversationArea .append("<div style='background-color: #FFC4C4;'>" + getDate(date) + " <b><font color='#16569e'>" + from + "</font></b>: " + message ); com.valhalla.jbother.sound.SoundPlayer .play("groupHighlightedSound"); if (!BuddyList.getInstance().getTabFrame().isFocused()) { NotificationPopup.showSingleton(BuddyList.getInstance() .getTabFrame(), resources .getString("messageReceived"), "<b>" + resources.getString("from") + ":</b> " + from,this); } highLightedSound = true; } else { conversationArea.append("" + getDate(date) + " <font color='#16569e'><b>" + from + "</b></font>: " + message ); } if (!highLightedSound) { com.valhalla.jbother.sound.SoundPlayer .play("groupReceivedSound"); if( Settings.getInstance().getBoolean("usePopup") && Settings.getInstance().getBoolean("popupForGroupMessage" )) { NotificationPopup.showSingleton(BuddyList.getInstance().getTabFrame(), resources .getString("groupMessageReceived"), from,this); } } } // fire MUCEvent for message received PluginChain.fireEvent(new MUCEvent(from, MUCEvent.EVENT_MESSAGE_RECEIVED, message, date)); int tabCount = BuddyList.getInstance().getTabFrame().markTab(this); try { TabbedPanel tabPane = BuddyList.getInstance().getTabFrame() .getTabPane(); if (tabPane.getSelectedTab().getContentComponent() != this && messageToMe) { String title = this.getShortRoomName() + " (" + tabCount + ")"; if (messageToMe) title = "*" + title; tab.setText(title); } } catch (Exception ex) { } } public void resetMessageToMe() { messageToMe = false; } /** * Closes the log file */ public void closeLog() { conversationArea.closeLog(); } /** * @return a String representing the current time the format: * [Hour:Minute:Second] */ public String getDate(Date d) { return ConversationPanel.getDate(d); } public MJTextField getSubjectField() { return subjectField; } /** * Sets the subject of the room * * @param subject * the subject to set */ public void setSubject(String subject) { this.subject = subject; if (BuddyList.getInstance().getTabFrame() != null) BuddyList.getInstance().getTabFrame().setSubject(this); subjectField.setText(subject); subjectField.setCaretPosition(0); subjectField.setToolTipText(subject); } /** * Returns the current room subject * * @return the current room subject */ public String getSubject() { return this.subject; } /** * Gets all the buddy statuses in the room * * @return all BuddyStatuses */ public Hashtable getBuddyStatuses() { return this.buddyStatuses; } /** * Sends the message currently in the textentryarea */ private void sendHandler() { String text = textEntryArea.getText(); Message message = chat.createMessage(); message.setBody(text); if (!textEntryArea.getText().equals("")) { try { chat.sendMessage(message); } catch (XMPPException e) { com.valhalla.Logger.debug("Could not send message."); } catch (IllegalStateException ex) { serverErrorMessage(resources.getString("notConnected")); } textEntryArea.setText(""); } } /** * Implementation of Tab nick completion in the textEntryArea */ private void nickCompletionHandler() { String text = textEntryArea.getText(); /* if we have nothing => do nothing */ if (!text.equals("")) { int caretPosition = textEntryArea.getCaretPosition(); int startPosition = text.lastIndexOf(" ", caretPosition - 1) + 1; String nickPart = text.substring(startPosition, caretPosition); Vector matches = new Vector(); java.util.List keys = new ArrayList(buddyStatuses.keySet()); Iterator iterator = keys.iterator(); while (iterator.hasNext()) { BuddyStatus buddy = (BuddyStatus) buddyStatuses.get(iterator .next()); if (!nickList.contains(buddy)) continue; try { String nick = buddy.getUser().substring( buddy.getUser().lastIndexOf("/") + 1); if (nick.toLowerCase().startsWith(nickPart.toLowerCase())) { matches.add(nick); } } catch (java.lang.NullPointerException e) { } } if (matches.size() > 0) { String append = ""; if (matches.size() > 1) { String nickPartNew = (String) matches.firstElement(); String nick = ""; String hint = nickPartNew + ", "; int nickPartLen = nickPart.length(); for (int i = 1; i < matches.size(); i++) { nick = (String) matches.get(i); hint += nick + ", "; for (int j = 1; j <= nick.length() - nickPartLen; j++) { if (!nickPartNew.regionMatches(true, nickPartLen, nick, nickPartLen, j)) { nickPartNew = nickPartNew.substring(0, nickPartLen + j - 1); break; } } } if (nickPart.length() != nickPartNew.length()) { nickPart = nickPartNew; } // emphasize differense in matches by bold and append hint // to the conversationArea // hint = hint.replaceAll() can't be used here because of // its case sensitive nature Pattern pattern = Pattern.compile("(" + nickPart + ")([^,]+), ", Pattern.CASE_INSENSITIVE); hint = pattern.matcher(hint).replaceAll("$1<b>$2</b>, "); conversationArea.append("<div style=\"color: #16569e;\">" + hint.substring(0, hint.length() - 2) ); } else { nickPart = (String) matches.firstElement(); if (startPosition == 0) append = ": "; else append = " "; } String newText = text.substring(0, startPosition); newText += nickPart + append; newText += text.substring(caretPosition); textEntryArea.setText(newText); /* Set caret to the appropriate position */ textEntryArea.setCaretPosition(startPosition + nickPart.length() + append.length()); } } /* end of the lazy "if" */ } /** * Joins the chatroom and adds this chatroomwindow to the TabFrame * * @author Adam Olsen * @version 1.0 */ class JoinChatThread extends Thread { private String errorMessage; private boolean cancelled = false; public void cancel() { interrupt(); cancelled = true; } public void run() { participantListener = new GroupParticipantListener(thisPointer); chat.addMessageListener(messageListener); chat.addParticipantListener(participantListener); chat.addSubjectUpdatedListener(subjectListener); chat.addParticipantStatusListener(statusListener); chat.addUserStatusListener(userStatusListener); try { chat.join(nickname, pass, new DiscussionHistory(), SmackConfiguration.getPacketReplyTimeout()); chat .addInvitationRejectionListener(new InvitationRejectionPacketListener()); } catch (XMPPException e) { if (!cancelled) { if (e.getXMPPError() == null) errorMessage = e.getMessage(); else errorMessage = resources.getString("xmppError" + e.getXMPPError().getCode()); } } if (!cancelled) { SwingUtilities.invokeLater(new Runnable() { public void run() { if (errorMessage != null) { serverErrorMessage(errorMessage); } else { if (cancelled) { errorMessage = "error"; } else { //set up a packet to be sent to my user in // every groupchat Presence presence = new Presence( Presence.Type.AVAILABLE, BuddyList .getInstance() .getCurrentStatusString(), 0, BuddyList.getInstance() .getCurrentPresenceMode()); presence.setTo(getRoomName() + '/' + getNickname()); BuddyList.getInstance().getConnection() .sendPacket(presence); } } } }); } else { errorMessage = "cancelled"; } if (errorMessage != null) { try { Thread.sleep(1000); leaveChat(); } catch (Exception neverCaught) { } } } }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -