2015-02-25 3 views
-1

Я пытаюсь настроить чат-клиент на качели.Swing Chat HTML форматированные сообщения

И мне это сообщение в истории корреспонденции было отформатировано в HTML.

Проблема, которую я попытался решить с помощью JTextPane, так как она поддерживает форматирование HTML.

Когда я это сделал, просто текстовый дисплей, в принципе все было нормально.

Но когда я начал, добавьте смайлики, используя тег HTML.

Каждый раз, новое сообщение, весь текст в окне корреспонденции подергивается как эпилепсик.

Как я это сделал.

jTextPane.setText ("message");

Когда это было, новое сообщение, я сделал так

jTextPane.setText ("сообщение" + "новое сообщение"); и т. д.

Результатом был принцип «змея» Тетриса.

В результате мне не понравилось, как это работает.

Так что, пожалуйста, скажите, можно ли выводить эти новые сообщения с помощью JLabel, добавляя их в JScrollpane?

Как сделать каждое новое сообщение отдельным элементом?


Привет! Я пытаюсь сделать чат клиент на swing.

И мне нужно, что сообщения в истории переписки были отформатированы в HTML.

Данную проблему я попробовал решить при помощи JTextPane, так как он поддерживает HTML форматирование.

Когда я сделал, просто отображение текста, впринципе все было нормально.

Но когда я начал, добавляю смайлики при помощи HTML тега.

При каждом новом сообщении весь текст в окне переписки дергался как эпилепсик.

Как я это делал.

jTextPane.setText ("message");

Когда приходило, новое сообщение, я делал так

jTextPane.setText ("сообщение" + "новое сообщение"); и т.д.

В итоге получился принцип "змейки" из тетриса.

В итоге мне не понравилось, как оно работает.

Так вот подскажите пожалуйста, можно ли как то выводить новые сообщения при помощи JLabel добавляя их в JScrollpane?

Как сделать, чтобы каждое новое сообщение было отдельным элементом?

String[] split = text.split("\t\t"); 

    String time = split[0].split("\t")[2].split(", ")[1]; 
    String sender = split[0].split("\t")[3]; 
    String message = split[1]; 

    if (!jTextPane.getText().equals("Please log in!")) { 
     oldMsg = jTextPane.getText().substring(jTextPane.getText().indexOf("<body>") + 6, jTextPane.getText().lastIndexOf("</body>")); 

     if(sender.equalsIgnoreCase(login.getText())) { 
      msg = "<div style=\"text-align:right\">" + checkMsgOnSmile(message) + " " + "<b>" + " :" + checkSenderOnColor(sender) + "</b>" + "<span style=\"font-size:10pt\">[" + time + "]</span></div>"; 
     } else { 
      msg = "<div style=\"\"><span style=\"font-size:10pt\">[" + time + "]</span> " + "<b>" + checkSenderOnColor(sender) + ":" + "</b>" + " " + checkMsgOnSmile(message); 
     } 

     String[] check = (oldMsg + msg).split("<br>"); 
     if (check.length > 99) { 
      ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(check)); 
      arrayList.remove(0); 
      String str = ""; 

      for (int i = 0; i < arrayList.size(); i++) { 
       str = str + arrayList.get(i).toString() + "<br>"; 
      } 

      jTextPane.setText(str); 
     } else { 
      oldMsg = oldMsg.replaceAll("<span><font size=\"10pt\">", "<span style=\"font-size:10pt\">"); 
      oldMsg = oldMsg.replaceAll("</font></span>", "</span>"); 
      jTextPane.setText(oldMsg + msg + "<br>"); 
     } 
    } 

Can it be replaced by a JLabel and JScrollPane?

ответ

2

If you just need to display text with different colors, fonts etc.., then I find working with text and attributes is easier than using HTML. A simple example would be code like:

JTextPane textPane = new JTextPane(); 
textPane.setText("Hello:"); 
textPane.setEditable(false); 
StyledDocument doc = textPane.getStyledDocument(); 

// Define a keyword attribute 

Simple AttributeSet keyWord = new SimpleAttributeSet(); 
StyleConstants.setForeground(keyWord, Color.RED); 
StyleConstants.setBackground(keyWord, Color.YELLOW); 
StyleConstants.setBold(keyWord, true); 

// Add some text 

try 
{ 
    doc.insertString(doc.getLength(), "\nAnother line of text", keyWord); 
} 
catch(Exception e) {} 
+0

I want get rid of the JTextPane. And make the display of new messages using JLabel. Can I make it so that when a new message arrives, create a new instance of JLabel it puts a new message, then this JLabel added to the JScrollPane. – Elsrix

+0

@Elsrix, Why would you use a JLabel? A JLabel is designed for simple text. A JTextPane is designed for styled text. – camickr

+0

sorry, i not fully checked everything! I thought that the JLabel, is also able to handle HTML tags, as well as JTextPane. Tell me, how do I optimize your code so that when a new message arrives, it gradually appeared in the history of correspondence? And now it is very choppy when a new message arrives. – Elsrix

Смежные вопросы