gpt4 book ai didi

java - 在 JTextPane 中绘制水平线

转载 作者:行者123 更新时间:2023-11-30 07:06:41 25 4
gpt4 key购买 nike

该问题似乎与 this one 重复但事实并非如此。因此,在否决这个问题之前,请澄清是否有任何混淆。

我想在我的 JTextPane 中每 6-7 行后绘制一条水平线 我正在使用 StyledDocument 并将字符串插入到我的 JTextPane在运行时。像这样的东西:

String myStr = "Some program-generated text";
doc.insertString(doc.getLength(), myStr, attributeSet);

现在如何每隔几行画一条水平线?我试过了

JTextPane textPane = new JTextPane();
textPane.setContentType("text/html");
textPane.setText("<html>Some Text Above The Line<hr size=5>Some Text Below</html>");

但目前我的应用程序使用 setContentType("text/plain"); 将其更改为 Text.html 会扰乱整个 UI。此外,如果我使用 SetText() 然后它将作为新文本插入,所有以前的文本都将消失,我附加了 doc.insertString();/p>

如有任何帮助,我们将不胜感激。

最佳答案

像这样!?

Screenshot of Sample Application

首先创建您自己的 JTextPane 子类。实现 draw 方法并使用 Graphics Context 中的 FontMetrics 来获取文本的高度。

public class MyTextPane extends JTextPane {

@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);

Graphics2D g2 = (Graphics2D) g;

g2.setColor(new Color(255, 0, 0, 128));

FontMetrics fm = g2.getFontMetrics();
int textHeight = fm.getHeight();

for (int i = textHeight; i < getHeight(); i += (6 * textHeight)) {
g2.drawLine(0, i + 1, getWidth(), i + 1);
}

g2.dispose();
}
}

关于java - 在 JTextPane 中绘制水平线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25535277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com