Java jTextPane 一行规则和粗体文本错位
Java jTextPane one line with regular and bold Text missplaced
我有一个使用 StyledDocument 的 TextPane。
如果键入一条消息,它首先将当前时间和其他用户 IP 添加到文档中
之后,用户输入的自定义消息会以粗体显示在其后面。
显然,问题是粗体占用了更多 space 并使其放错位置,从而导致:
<- 目前所以用于此过程的代码如下:
public void addText(String msg) {
long timeMS = System.currentTimeMillis();
Date instant = new Date(timeMS);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String time = sdf.format(instant);
SimpleAttributeSet bold = new SimpleAttributeSet();
StyleConstants.setBold(bold, true);
try {
StyledDocument doc = getChat().getStyledDocument();
doc.insertString(doc.getLength(), time + ": " + Client.getClient().getPartnerIP() + " >>", null);
doc.insertString(doc.getLength(), msg + "", bold);
JScrollBar sb = getChatScroller().getVerticalScrollBar();
sb.setValue(sb.getMaximum());
} catch (BadLocationException e) {
e.printStackTrace();
}
}
我知道使用 htmlEditorKit 可以轻松解决这个问题,但我不想使用 htmlEditorKit。
我说过我不想使用我现在使用的 HTMLEditorKit,因为它是我能找到的唯一修复程序。
这是我目前的工作方式:
public void addMsg(String msg, String from) {
String formattedMessage = String.format("%s%s<font color=#FF0000 size=5><b>%s</b></font>\n", from, (from == getUserName() ? " >>" : " <<"), msg);
addText(formattedMessage, true);
}
并且不要忘记在 TextPane 上设置 EditorKit!
chat.setEditorKit(new HTMLEditorKit());
我有一个使用 StyledDocument 的 TextPane。 如果键入一条消息,它首先将当前时间和其他用户 IP 添加到文档中 之后,用户输入的自定义消息会以粗体显示在其后面。
显然,问题是粗体占用了更多 space 并使其放错位置,从而导致:
public void addText(String msg) {
long timeMS = System.currentTimeMillis();
Date instant = new Date(timeMS);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String time = sdf.format(instant);
SimpleAttributeSet bold = new SimpleAttributeSet();
StyleConstants.setBold(bold, true);
try {
StyledDocument doc = getChat().getStyledDocument();
doc.insertString(doc.getLength(), time + ": " + Client.getClient().getPartnerIP() + " >>", null);
doc.insertString(doc.getLength(), msg + "", bold);
JScrollBar sb = getChatScroller().getVerticalScrollBar();
sb.setValue(sb.getMaximum());
} catch (BadLocationException e) {
e.printStackTrace();
}
}
我知道使用 htmlEditorKit 可以轻松解决这个问题,但我不想使用 htmlEditorKit。
我说过我不想使用我现在使用的 HTMLEditorKit,因为它是我能找到的唯一修复程序。
这是我目前的工作方式:
public void addMsg(String msg, String from) {
String formattedMessage = String.format("%s%s<font color=#FF0000 size=5><b>%s</b></font>\n", from, (from == getUserName() ? " >>" : " <<"), msg);
addText(formattedMessage, true);
}
并且不要忘记在 TextPane 上设置 EditorKit!
chat.setEditorKit(new HTMLEditorKit());