Java 如何在chatserver中包含表情符号

Java 如何在chatserver中包含表情符号,java,Java,有人能帮助我如何在代码中包含表情符号吗 import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import javax

有人能帮助我如何在代码中包含表情符号吗

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
/**
* A simple Swing-based client for the chat server. Graphically
* it is a frame with a text field for entering messages and a
* textarea to see the whole dialog.
*
* The client follows the Chat Protocol which is as follows.
* When the server sends "SUBMITNAME" the client replies with the
* desired screen name. The server will keep sending "SUBMITNAME"
* requests as long as the client submits screen names that are
* already in use. When the server sends a line beginning
* with "NAMEACCEPTED" the client is now allowed to start
* sending the server arbitrary strings to be broadcast to all
* chatters connected to the server. When the server sends a
* line beginning with "MESSAGE " then all characters following
* this string should be displayed in its message area.
*/

public class ChatClient {

BufferedReader in;
PrintWriter out;

JFrame frame = new JFrame("Chatter");
JTextField textField = new JTextField(40);

JTextArea messageArea = new JTextArea(8, 40);

/**

* Constructs the client by laying out the GUI and registering a
* listener with the textfield so that pressing Return in the
* listener sends the textfield contents to the server. Note
* however that the textfield is initially NOT editable, and
* only becomes editable AFTER the client receives the NAMEACCEPTED
* message from the server.
*/

public ChatClient() {

// Layout GUI
textField.setEditable(false);

messageArea.setEditable(false);
frame.getContentPane().add(textField, "North");
frame.getContentPane().add(new JScrollPane(messageArea), "Center");
frame.pack();

// Add Listeners
textField.addActionListener(new ActionListener() {

/**
* Responds to pressing the enter key in the textfield by sending
* the contents of the text field to the server. Then clear
* the text area in preparation for the next message.
*/

public void actionPerformed(ActionEvent e) {
  out.println(textField.getText());
  textField.setText("");
}

});

}

/**
* Prompt for and return the address of the server.
*/
private String getServerAddress() {
  return JOptionPane.showInputDialog(
    frame,
    "Enter IP Address of the Server:",
    "Welcome to the Chatter",
    JOptionPane.QUESTION_MESSAGE);
}

/**
* Prompt for and return the desired screen name.
*/
private String getName() {
  return JOptionPane.showInputDialog(
    frame,
    "Choose a screen name:",
    "Screen name selection",
    JOptionPane.PLAIN_MESSAGE);
}

/**
* Connects to the server then enters the processing loop.
*/
private void run() throws IOException {
  // Make connection and initialize streams
  String serverAddress = getServerAddress();
  Socket socket = new Socket(serverAddress, 9001);
  in = new BufferedReader(new InputStreamReader(
  socket.getInputStream()));
  out = new PrintWriter(socket.getOutputStream(), true);
  // Process all messages from server, according to the protocol.
  while (true) {
    String line = in.readLine();
    if (line.startsWith("SUBMITNAME")) {
      out.println(getName());
    } else if (line.startsWith("NAMEACCEPTED")) {
      textField.setEditable(true);
    } else if (line.startsWith("MESSAGE")) {
      messageArea.append(line.substring(8) + "\n");
    }
  }
}

/**
* Runs the client as an application with a closeable frame.
*/
public static void main(String[] args) throws Exception {
  ChatClient client = new ChatClient();
  client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  client.frame.setVisible(true);
  client.run();
}
}

首先,我并不认为你的代码是诚实的,但是你要问的是一些非常简单的问题。你注意到所有的表情符号都有一系列的字符吗

Skype示例::*:y。。。等等

编译消息时,会发生一个简单的replaceAll

String message = "Of course :)";
// in this place here you will make a loop for all your emoticons or just 
// match it by regex.
message = message.replaceAll(":)", imageToAdd);

sendMessage(message);

这基本上就是在聊天中添加表情符号时发生的情况。您可以使用HashMap to,其中id是字符序列,值是该表情符号的路径或图像组件。如果你有几个

就快多了。你的代码没有砸我的头,但我在聊天室里用的是:

在窗格中用适当的图像自动替换微笑文本

为了支持自动替换,我们需要一个带有StyledEditorKit或扩展类的JEditorPane来提供文本图像。我们只需添加一个DocumentListener来处理文本插入事件。插入后,我们检查更改的文本是否包含字符串-字符串:。如果它包含微笑文本,我们将用适当的图像替换它

该示例仅提供一个微笑支持:字符串,但可以轻松扩展

注意:我们应该用SwingUtilities.invokeLater包围我们的代码,因为我们不能在侦听器中截获的变异期间更改文档

The example code is below:

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.*;
import java.awt.image.BufferedImage;
import java.awt.*;

public class AutoreplaceSmiles extends JEditorPane {
    static ImageIcon SMILE_IMG=createImage();

    public static void main(String[] args) {
        JFrame frame = new JFrame("Autoreplace :) with Smiles images example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final AutoreplaceSmiles app = new AutoreplaceSmiles();
        app.setEditorKit(new StyledEditorKit());
        app.initListener();
        JScrollPane scroll = new JScrollPane(app);
        frame.getContentPane().add(scroll);

        frame.setSize(400, 200);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public AutoreplaceSmiles() {
        super();
    }

    private void initListener() {
        getDocument().addDocumentListener(new DocumentListener(){
            public void insertUpdate(DocumentEvent event) {
                final DocumentEvent e=event;
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        if (e.getDocument() instanceof StyledDocument) {
                            try {
                                StyledDocument doc=(StyledDocument)e.getDocument();
                                int start= Utilities.getRowStart(AutoreplaceSmiles.this,Math.max(0,e.getOffset()-1));
                                int end=Utilities.getWordStart(AutoreplaceSmiles.this,e.getOffset()+e.getLength());
                                String text=doc.getText(start, end-start);

                                int i=text.indexOf(":)");
                                while(i>=0) {
                                    final SimpleAttributeSet attrs=new SimpleAttributeSet(
                                       doc.getCharacterElement(start+i).getAttributes());
                                    if (StyleConstants.getIcon(attrs)==null) {
                                        StyleConstants.setIcon(attrs, SMILE_IMG);
                                        doc.remove(start+i, 2);
                                        doc.insertString(start+i,":)", attrs);
                                    }
                                    i=text.indexOf(":)", i+2);
                                }
                            } catch (BadLocationException e1) {
                                e1.printStackTrace();
                            }
                        }
                    }
                });
            }
            public void removeUpdate(DocumentEvent e) {
            }
            public void changedUpdate(DocumentEvent e) {
            }
        });
    }

    static ImageIcon createImage() {
        BufferedImage res=new BufferedImage(17, 17, BufferedImage.TYPE_INT_ARGB);
        Graphics g=res.getGraphics();
        ((Graphics2D)g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setColor(Color.yellow);
        g.fillOval(0,0,16,16);

        g.setColor(Color.black);
        g.drawOval(0,0,16,16);

        g.drawLine(4,5, 6,5);
        g.drawLine(4,6, 6,6);

        g.drawLine(11,5, 9,5);
        g.drawLine(11,6, 9,6);

        g.drawLine(4,10, 8,12);
        g.drawLine(8,12, 12,10);
        g.dispose();

        return new ImageIcon(res);
    }
}

imageToAdd是什么?这将是将发生的图像,而不是字符序列。例如,如果您在web中执行此操作,它将是一个标记。这是替换的正确方法吗,str=str.replaceAll:,smiliesgeneral3_640x480.jpgs;只需添加图像名称???这是什么伴侣?您尝试过什么,请不要发布完整的代码/首先检查代码的工作方式自己尝试一下,然后发布您遇到困难的部分的问题?