2016-01-28 51 views
1

我有一个使用StyledDocument的TextPane。 如果输入消息,则首先将当前时间和其他用户IP添加到文档中。 然后,用户输入的自定义消息以粗体添加。Java jTextPane具有常规和粗体文本错位的一行

显然的问题是,大胆的占用更多的空间,使得它放错位置造成的: enter image description here < - 目前所以用于该方法的代码如下:

public void addText(String msg) { 
 

 
\t long timeMS = System.currentTimeMillis(); 
 
\t Date instant = new Date(timeMS); 
 
\t SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); 
 
\t String time = sdf.format(instant); 
 
\t SimpleAttributeSet bold = new SimpleAttributeSet(); 
 
\t StyleConstants.setBold(bold, true); 
 
\t try { 
 
\t  StyledDocument doc = getChat().getStyledDocument(); 
 
\t  doc.insertString(doc.getLength(), time + ": " + Client.getClient().getPartnerIP() + " >>", null); 
 
\t  doc.insertString(doc.getLength(), msg + "", bold); 
 
\t  JScrollBar sb = getChatScroller().getVerticalScrollBar(); 
 
\t  sb.setValue(sb.getMaximum()); 
 
\t } catch (BadLocationException e) { 
 
\t  e.printStackTrace(); 
 
\t } 
 
    }

我知道这可以很容易地使用htmlEditorKit修复,但我不想使用htmlEditorKit。

+0

我没有看到任何发布代码的问题。请添加SSCCE示例让我们运行并重现问题, – StanislavL

+0

我通过使用HTMLEditorKit修复了它,并将整个字符串格式化为一个html行 – durchstarter

回答

0

Eventho我说我不想使用我现在使用的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() ? " >>" : " &lt;&lt;"), msg); 
addText(formattedMessage, true); 
} 

不要忘记设置在TextPane EditorKit来!

chat.setEditorKit(new HTMLEditorKit()); 
相关问题