使用 .setText 方法时 JTextPane 文本下的空格



我正在使用MigLayout 3.5.5,因为较新的更新与我的旧代码不兼容。

问题

将文本设置为MigLayout中的JTextPane时,如果我正在设置JTextPane的文本包含空格字符,则JTextPane将占用双倍的空间(根据字体大小)。它不会一直发生,但在我正在制作的特定程序中,它经常发生。

该程序的目标是以逐个字母的方式呈现信息,因此有一个按钮可以将文本更新为下一个字母。但是,文本会跳动,因为JTextPane有时会比平时占用更多的空间。我确定了高度差异的某种模式。

模式

新行表示我添加了一个字母.
"|" 表示文本中的空格字符。
"空格"表示占用了两倍的空间JTextPane
Full String:"敏捷的棕色狐狸跳过懒惰的狗。

T
Th
The
The|
The|q (Space)
The|qu
The|qui (Space)
The|quic

The|quick(Space)
The|quick|

注意:我在这里停止了模式,因为从这一点开始(从 The|quick|b 开始),每个字母的添加都会导致JTextPane占据其高度的两倍。

我已经尝试将逐个字母的文本打印到控制台,以查看要添加的文本中是否有任何新行字符,但无济于事。我也认为这可能是JTextPane自动换行的问题,但我插入的文本不够长,无法换行JFrame的大小。

下面是重现该行为的简短示例:

public class MainFrame extends JFrame {
int currentLetter = 1;
final String FULL_TEXT = "The quick brown fox jumps over the lazy dog.";

JTextPane text;
JButton addLetter;

MainFrame() {

setSize(500, 500);
setLayout(new MigLayout("align center, ins 0, gap 0"));
addElements();

setVisible(true);

}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

public void run() {

MainFrame application = new MainFrame();

}

});

}

private void addElements() {

text = new JTextPane();
text.setEditable(false);
text.setFont(new Font("Times New Roman", Font.BOLD, 19));
text.setForeground(Color.WHITE);
text.setBackground(Color.BLACK);
add(text, "alignx center, wmax 80%, gapbottom 5%");

addLetter = new JButton("Add Letter");

addLetter.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

if (currentLetter != FULL_TEXT.length()) {

currentLetter++;
updateText();

}

}

});

add(addLetter, "newline, alignx center");

updateText();

}

private void updateText() {

String partialText = new String();

for (int letter = 0; letter < currentLetter; letter++) {

partialText += FULL_TEXT.toCharArray()[letter];

}

text.setText(partialText);
}
}

我为什么要使用JTextPane

我尝试使用JLabel来完成此任务,效果很好......直到文本足够长,可以换行。然后,当我在JLabel文本中使用 HTML 来包装它时,每次更新文本时,HTML 都需要一些时间来呈现并导致一些非常讨厌的视觉效果。

接下来,我试图JTextArea将其伪装成JLabel,因为它不仅具有换行功能,还具有自动换行功能。这是一个很好的解决方案,直到我发现我不能在JTextArea中使用中心段落对齐方式。

所以我选择了JTextPane,只要我去掉底部的额外空间,它就会很好地工作。

提前感谢您的帮助!

解决方案是通过在 JTextPane 的 StyledDocument 上使用 insertString() 方法附加文本,而不是在 JTextPane 本身上使用 setText()。

例如,改为每次都这样做:

JTextPane panel = new JTextPane();
panel.setText(panel.getText() + "test");

您应该这样做:

JTextPane panel = new JTextPane();
StyledDocument document = panel.getStyledDocument();
document.insertString(document.getLength(), "test", null);

当然,你需要抓住BadLocationException。

然后空间消失了。这是我找到渲染问题答案的问题:JTextPane附加一个新字符串

这些问题的答案并不能解决空间问题,但它们确实显示了在 JTextPane 中编辑文本的正确方法。

最新更新