package my;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;
import org.json.JSONObject;
public class MsgBox extends JTextPane
{
List<Item> itemList = new ArrayList<>();
public MsgBox()
{
initDocStyle(this.getStyledDocument());
this.setEditable(false);
}
// 添加几个样式 name, time, content
private void initDocStyle(StyledDocument doc)
{
Style def = StyleContext.getDefaultStyleContext().
getStyle(StyleContext.DEFAULT_STYLE);
if(true)
{
Style s = doc.addStyle("name", def);
StyleConstants.setFontFamily(s, "宋体");
StyleConstants.setBold(s, true);
StyleConstants.setFontSize(s, 12);
}
if(true)
{
Style s = doc.addStyle("time", def);
StyleConstants.setFontFamily(s, "宋体");
StyleConstants.setBold(s, true);
StyleConstants.setFontSize(s, 12);
}
if(true)
{
Style s = doc.addStyle("content", def);
StyleConstants.setFontFamily(s, "宋体");
StyleConstants.setBold(s, false);
StyleConstants.setFontSize(s, 14);
}
}
// 添加一条消息
public void appendMessage(JSONObject msg)
{
String name = msg.optString("name", "");
String time = msg.optString("time", "");
String content = msg.optString("content", "");
StyledDocument doc = getStyledDocument();
try
{
Item item = new Item();
String text = name;
doc.insertString(doc.getLength(), text, doc.getStyle("name"));
item.length += text.length();
text = " " + time +"\n";
doc.insertString(doc.getLength(),text , doc.getStyle("time"));
item.length += text.length();
text = " " + content + "\n\n" ;
doc.insertString(doc.getLength(), text, doc.getStyle("content"));
item.length += text.length();
itemList.add(item);
} catch (BadLocationException e)
{
e.printStackTrace();
}
// 当消息太多时,删除前面的消息
if(itemList.size() > 40)
{
Item item = itemList.get(0);
itemList.remove(0);
try
{
doc.remove(0, item.length);
} catch (BadLocationException e)
{
e.printStackTrace();
}
}
}
// 记录每一段消息的位置,方便清理删除
private static class Item
{
int length;
}
}
评论0