2016-01-28 49 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()); 
相關問題