【发布时间】:2015-07-12 17:06:39
【问题描述】:
嘿,我正在制作一个聊天应用程序,最初使用一个简单的 JTextPane 作为基本的、支持颜色的聊天视图窗格。然后我想通过添加 HTML 侦听器并将内容类型设置为 text/html 来添加 html 链接支持以使它们可点击。可点击的链接完美地工作,但现在每次我插入一个字符串时,聊天都会增加一个很大的空间。这是我在下面使用的代码:
构造函数:
public JTextPaneTest() {
this.addHyperlinkListener(new LinkController());
this.setContentType("text/html");
this.setEditable(false);
}
这是我添加常规文本的方法:
public void append(Color c, String s) {
SimpleAttributeSet sas = new SimpleAttributeSet();
StyleConstants.setForeground(sas, c);
StyledDocument doc = (StyledDocument)this.getDocument();
int len = getDocument().getLength();
try {
doc.insertString(len, s, sas);
} catch (BadLocationException e) {
e.printStackTrace();
}
setCaretPosition(len + s.length());
}
这是我插入链接的方式
public void addHyperlink(URL url, String text) {
try {
Document doc = this.getDocument();
SimpleAttributeSet hrefAttr = new SimpleAttributeSet();
hrefAttr.addAttribute(HTML.Attribute.HREF, url.toString());
SimpleAttributeSet attrs = new SimpleAttributeSet();
attrs.addAttribute(HTML.Tag.A, hrefAttr);
StyleConstants.setUnderline(attrs, true);
StyleConstants.setForeground(attrs, Color.blue);
doc.insertString(doc.getLength(), text, attrs);
}
catch (BadLocationException e) {
e.printStackTrace(System.err);
}
}
无论出于何种原因将内容类型设置为基本文本,我都没有遇到这个空间问题。
以下是它的一些图片: http://i.stack.imgur.com/dpMBB.png
在图片中,插入了名称,然后是:,然后是其余的文本。
编辑:无论出于何种原因,JTextPane 都会自动将我的 InsertStrings 居中。
Edit2:是否可以删除 HTML 插入字符串之间的边距?我已经连续尝试了几个小时,但根本找不到解决方案。我能想到的唯一可能的解决方案是每次插入字符串时通过 getText/setText 重新格式化文本以确保不添加边距。..
【问题讨论】:
-
您打算很快发布 MCVE 吗?
-
@Andrew Thompson 我添加了更多(构造函数)。你还想让我补充什么?
-
我猜这是无法修复的?每次我插入一个新字符串时,都会创建一个 HTML。然后插入的字符串彼此间隔开,就好像我有一个边距一样。有什么办法可以去掉边距?如果我要切换语言,这让我发疯了......
-
这不是关于我“喜欢”什么,而是你是否需要帮助,如果需要,需要多少。现在点击 SSCCE 的链接并仔细阅读文档,因为不可编译的代码 sn-ps 不适用于 MCVE/SSCCE!
标签: java html swing jframe jtextpane